Created
July 19, 2016 17:02
-
-
Save bradbeattie/a0d297e088dde56b7bda7a5e3e298de0 to your computer and use it in GitHub Desktop.
Django queryset understanding confirmation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#$ 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