Last active
August 29, 2015 14:07
-
-
Save scottsexton/375f7869839a98593695 to your computer and use it in GitHub Desktop.
Q Filter behavior change between Django 1.6.7 and Django 1.7
This file contains 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
+------------+ | |
| Owners | | |
+----+-------+ | |
|id |name | | |
+----+-------+ | |
| 1 |Alice | | |
+----+-------+ | |
| 2 |Bob | | |
+----+-------+ | |
| 3 |Steve | | |
+----+-------+ | |
+-------------------+ | |
| Pets | | |
+----+------+-------+ | |
|id |name |flies | | |
+----+------+-------+ | |
| 1 |Dog |0 | | |
+----+------+-------+ | |
| 2 |Cat |0 | | |
+----+------+-------+ | |
| 3 |Bird |1 | | |
+----+------+-------+ | |
+---------------------------------+ | |
| PetOwners | | |
+----+----------+--------+--------+ | |
|id |owner_id |pet_id |name | | |
+----+----------+--------+--------+ | |
| 1 | 1 | 1 |Rover | | |
+----+----------+--------+--------+ | |
| 2 | 1 | 3 |Birdo | | |
+----+----------+--------+--------+ | |
| 3 | 2 | 2 |Lion-o | | |
+----+----------+--------+--------+ | |
| 4 | 3 | 3 |Polly | | |
+----+----------+--------+--------+ |
This file contains 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
from django.db import models | |
class Owner(models.Model): | |
name = models.CharField(max_length=30) | |
def __unicode__(self): | |
return self.name | |
class Pet(models.Model): | |
name = models.CharField(max_length=30) | |
flies = models.BooleanField(default=False) | |
class PetOwner(models.Model): | |
owner = models.ForeignKey(Owner) | |
pet = models.ForeignKey(Pet) | |
name = models.CharField(max_length=30) |
This file contains 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
>>> from django.db.models import Q | |
>>> from myapp.models import Owner, Pet, PetOwner | |
>>> # Get owners who only have pets that can't fly. (Expected: <Owner: Bob>) | |
>>> q_obj = Q(Q(petowner__pet__flies=False), ~Q(petowner__pet__flies=True)) | |
### In Django 1.6 ### | |
>>> Owner.objects.filter(q_obj) | |
[<Owner: Bob>] | |
### In Django 1.7 ### | |
>>> Owner.objects.filter(q_obj) | |
[<Owner: Alice>, <Owner: Bob>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment