Skip to content

Instantly share code, notes, and snippets.

@scottsexton
Last active August 29, 2015 14:07
Show Gist options
  • Save scottsexton/375f7869839a98593695 to your computer and use it in GitHub Desktop.
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
+------------+
| 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 |
+----+----------+--------+--------+
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)
>>> 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