简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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