Skip to content

Instantly share code, notes, and snippets.

@bradbeattie
Created July 19, 2016 17:02
Show Gist options
  • Save bradbeattie/a0d297e088dde56b7bda7a5e3e298de0 to your computer and use it in GitHub Desktop.
Save bradbeattie/a0d297e088dde56b7bda7a5e3e298de0 to your computer and use it in GitHub Desktop.
Django queryset understanding confirmation
#$ cat myapp/models.py
#from django.db import models
#
#class Foo(models.Model):
# pass
#
#class Bar(models.Model):
# foos = models.ManyToManyField(Foo, related_name="bars")
# val_a = models.BooleanField()
# val_b = models.BooleanField()
# Ensure we're working on an empty set
Foo.objects.all().delete()
Bar.objects.all().delete()
# Create two Foo objects
fooA = Foo()
fooA.save()
fooB = Foo()
fooB.save()
# Create Bar objects with alternating values
bar_01 = Bar(val_a=False, val_b=True)
bar_01.save()
bar_10 = Bar(val_a=True, val_b=False)
bar_10.save()
bar_11 = Bar(val_a=True, val_b=True)
bar_11.save()
# Join to foos and the bars
fooA.bars.add(bar_01)
fooA.bars.add(bar_10)
fooB.bars.add(bar_11)
# Ensure sane joined filter results
queryset = Foo.objects.filter(bars__val_a=True, bars__val_b=True)
assert fooA not in queryset
assert fooB in queryset
# Ensure sane separate filter results
queryset = Foo.objects.filter(bars__val_a=True).filter(bars__val_b=True)
assert fooA in queryset
assert fooB in queryset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment