简体   繁体   English

如何结合多个Django queryset聚合和过滤器

[英]how to combine multiple django queryset aggregates and filters

I have the following problem: 我有以下问题:

class species(models.Model):
  pass

class question(models.Model):
  species = models.ForeignKey(species)

class answer(models.Model):
  question = models.ForeignKey(question)

Now I'd like to retrieve a queryset of species that contain any question that do not have any answers. 现在,我想检索包含没有任何答案的任何问题物种的查询集。

I mean I can get all species that have questions by using: 我的意思是,我可以使用以下方法获得所有有疑问的物种:

sp = species.objects.annotate(num_questions=Count('question')).filter(
    num_questions__gt=0)

Also I can get all questions that do not have answers using: 我也可以使用以下方法获得所有没有答案的问题:

qs = question.objects.annotate(num_answers=Count('answer')).filter(
    num_answers=0)

But how do I combine the two things together? 但是,如何将这两件事结合在一起?

thanks in advance! 提前致谢!

You can daisy-chain annotations like so: 您可以像这样通过菊花链方式注释:

sp = species.objects.annotate(num_questions=Count('question')).annotate(
          num_answers=Count('answer')).filter(num_questions__gt=0, num_answers=0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM