我正在使用filter()
和exclude()
进行查询,具体取决于用户的搜索条件。如果指定,我也根据搜索对查询进行排序。一切正常,除非用户使用exclude()
函数并尝试在related_field
中排序。但它适用于filter()
。
我正在使用Django 1.10和Postgresql
简化的模型如下:
class Project(models.Model):
name = models.CharField(max_length=175)
class Meta:
ordering = ['name']
db_table = 'project'
class Summary(models.Model):
mykey = models.CharField(max_length=20, primary_key=True)
external_order_id = models.ManyToManyField('Project', blank=True)
查询
project = InventoryProject.objects.get(name='')
# with exclude
# this one returns [], but if I do .count() it returns the correct number of rows
queryset.annotate(num_projects=Count('external_order_id')).exclude(external_order_id=project, num_projects=1).order_by('external_order_id')
# with filter
# this one works like a charm
queryset = queryset.annotate(num_projects=Count('external_order_id')).filter(external_order_id=project, num_projects=1)
我在订单之前和之后检查了.query
属性,它们看起来非常不同
// before (it shows all the data)
SELECT "summary"."mykey",
COUNT("summary_external_order_id"."project_id") AS "num_projects"
FROM "summary"
LEFT OUTER JOIN "summary_external_order_id" ON ("summary"."mykey" = "summary_external_order_id"."summary_id")
GROUP BY "summary"."mykey"
HAVING NOT ("summary"."mykey" IN
(SELECT U1."summary_id" AS Col1 FROM "summary_external_order_id" U1 WHERE U1."project_id" = 1) AND COUNT("summary_external_order_id"."project_id") = 1)
// after (doesn't show any data)
SELECT "summary"."mykey",
COUNT("summary_external_order_id"."project_id") AS "num_projects"
FROM "summary"
LEFT OUTER JOIN "summary_external_order_id" ON ("summary"."mykey" = "summary_external_order_id"."summary_id")
LEFT OUTER JOIN "project" ON ("summary_external_order_id"."project_id" = "project"."id")
GROUP BY "summary"."mykey", "project"."name"
HAVING NOT ("summary"."mykey" IN
(SELECT U1."summary_id" AS Col1 FROM "summary_external_order_id" U1 WHERE U1."project_id" = 1) AND COUNT("summary_external_order_id"."project_id") = 1)
ORDER BY "project"."name" ASC
我不确定为什么django会自动按'mykey'分组。此外,如果我删除“项目”。“名称”来自该组的工作......
修改: 这里要求的是“项目”表的数据,其中ID为1
id [pk] - integer | name - character varying(175)
1 |