Getting a count of objects in a queryset in django

前端 未结 3 1821
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 04:40

How can I add a field for the count of objects in a database. I have the following models:

class Item(models.Model):
    name = models.CharField()

class Con         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-24 05:15

    Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

    Item.objects.values("contest").annotate(Count("id"))
    

    I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

提交回复
热议问题