这两个基于Django Q的查询有什么区别:

时间:2011-11-17 19:04:29

标签: django django-queryset django-q

假设这样一个简单的模型:

class Item(models.Model): 
    name = models.CharField(max_length=10)

class Relation(models.Model):
    item = models.ForeignKey(Item)
    weight = models.IntegerField() 

这样的几个Q对象:

some = Q(relation__x__gt=3)
others = Q(relation__x=7)

之间的语义差异是什么:

first = Item.objects.filter(some, ~others)

second = Item.objects.filter(some).exclude(others) 

注意:查询关系似乎与查询单个简单对象不同。为上述两个查询生成的SQL是不同的。

这是首先生成的SQL:

SELECT "item_item"."id", "item_item"."name" 
FROM "item_item" 
INNER JOIN "item_relation" 
ON ("item_item"."id" = "item_relation"."item_id") 
WHERE ("item_relation"."weight" > 3  
  AND NOT ("item_item"."id" IN 
    (SELECT U1."item_id" 
     FROM "item_relation" U1 
     WHERE (U1."weight" = 7  AND U1."item_id" IS NOT NULL))))

SQL for second:

SELECT "item_item"."id", "item_item"."name" 
FROM "item_item" 
INNER JOIN "item_relation" 
ON ("item_item"."id" = "item_relation"."item_id") 
INNER JOIN "item_relation" T3 
ON ("item_item"."id" = T3."item_id") 
WHERE ("item_relation"."weight" > 3  AND NOT (T3."weight" = 7 ))

0 个答案:

没有答案