如何按Django中另一个表中的出现次数过滤?

时间:2018-10-09 23:48:21

标签: django postgresql django-models

这是我的模特:

class Zoo(TimeStampedModel):
    id = models.AutoField(primary_key=True)

class Animal(models.Model):
    id = models.AutoField(primary_key=True)
    zoo = models.ForeignKey(Zoo, on_delete=models.PROTECT, related_name='diffbot_results')

我想运行这样的查询:

Zoo.objects.filter("WHERE zoo.id IN (select zoo_id from animal_table having count(*) > 10 group by zoo_id)")

1 个答案:

答案 0 :(得分:0)

一种方法是使用raw queryset

>>> from testapp.models import Zoo, Animal
>>> z1, z2 = Zoo(), Zoo()
>>> z1.save(), z2.save()
(None, None)
>>> z1_animals = [Animal(zoo=z1) for ii in range(5)]
>>> z2_animals = [Animal(zoo=z2) for ii in range(15)]
>>> x = [a.save() for a in z1_animals+z2_animals]
>>> qs = Zoo.objects.raw("select * from testapp_zoo zoo WHERE zoo.id IN (select zoo_id from testapp_animal group by zoo_id having count(1) > 10)")
>>> list(qs)
[<Zoo: Zoo object (2)>]

理论上,每these docs都可以将查询集传递给常规.filter(id__in=<queryset>),但是查询集只能选择一个列,而我找不到添加方法HAVING子句,也不会导致queryset选择num_animals列,从而阻止它与__in过滤器表达式一起使用。