开发者

Django aggregate count on ForeignKey returning multiple records for same ID

The model structure is Question has one Video, and Question has many Answers.

The problem query is:

questions = Question.objects\
  .values('id', 'answer', 'section__title', 'title', 'created_at','user__username')\
  .filter(video=v).annotate(answer_count=Count('answer'))

I'm using the Count aggregate function to add an extra field to say how many answers a question has.

It works fine for zero and one answers. But if a question has three answers, I get three different rows back with the same ID, wit开发者_开发问答h answer_count=1 and different IDs for the 'answer' field.

What am I doing wrong?


I'm not sure what your model definition is. I assume you have something like this:

class Answer(models.Models):
    question = models.ForeignKey(Question, related_name='answer')

When you query the way you described, you will retrieve one row per answer. If you leave out 'answer', from the values call, you should get what you wanted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜