简体   繁体   English

如何在django中使用queryset计算字典的值

[英]How to count the value of dictionary using queryset in django

I used .value('post_id') in django to bring the following values.我在 django 中使用 .value('post_id') 来带来以下值。

<QuerySet [{'post_id': 3}, {'post_id': 2}, {'post_id': 1}, {'post_id': 3}]>

If you count the value of each dictionary, you will have one, one, and two, respectively.如果算上每本字典的值,就会分别有1、1、2。 Which queryset should I look for, instead of counting it as a queryset without for loop ?我应该寻找哪个查询集,而不是将它算作没有 for 循环的查询集?

models.py模型.py

class Like (models.Model) :
    liked_people = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='liked_people', null=True)

You should annotate the target model, so:您应该注释目标模型,因此:

from django.db.models import Count

Post.objects.annotate(
    number_of_liked=Count('liked_people')
)

The Post objects that arise from this will have an extra attribute .number_of_liked that contains the number of related Liked s.由此产生的Post对象将有一个额外的属性.number_of_liked ,其中包含相关Liked的数量。

You can further filter the Like objects, for example with:您可以进一步过滤Like对象,例如:

from django.db.models import Count

Post.objects.filter(
    liked_people__liked_people=my_user
).annotate(
    number_of_liked=Count('liked_people')
)

This will exclude Post objects that have no related Like objects with liked_people=my_user .这将排除没有与liked_people=my_user相关的Like对象的Post对象。 You can also include these, but then with .number_of_liked = 0 , with:你也可以包括这些,但是用.number_of_liked = 0 ,用:

from django.db.models import Count, Q

Post.objects.annotate(
    number_of_liked=Count(
        'liked_people', filter=Q(liked_people__liked_people=my_user)
    )
)

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

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