Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Django queryset understanding confirmation
#$ cat myapp/
#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
# Create two Foo objects
fooA = Foo()
fooB = Foo()
# Create Bar objects with alternating values
bar_01 = Bar(val_a=False, val_b=True)
bar_10 = Bar(val_a=True, val_b=False)
bar_11 = Bar(val_a=True, val_b=True)
# Join to foos and the bars
# 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
You can’t perform that action at this time.