[英]How to annotate on a single object and not a QuerySet in Django?
When annotating something to a model in Django one would write something like this:在 Django 中为模型注释某些内容时,会写如下内容:
Post.objects.all().annotate(total_yes_votes=Count('vote', filter=Q(vote__vote_choice='yes')))
What if I want to annotate on a single object and not all() the objects:如果我想对单个对象进行注释而不是对所有对象进行注释怎么办:
Post.objects.get(id=id).annotate(total_yes_votes=Count('vote', filter=Q(vote__vote_choice='yes')))
By the way, it doesn't work.顺便说一下,它不起作用。
Isn't it more efficient to annotate a single object rather than all()?注释单个对象不是比 all() 更有效吗?
将调用.get()
移到注释之后
Post.objects.annotate(total_yes_votes=Count('vote', filter=Q(vote__vote_choice='yes'))).get(id=id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.