简体   繁体   中英

Django model with Charfield Count and Zero values

I have a Django database model that has some attributes, one of them is a Charfield 'category' with Choices. I now want to annotate a queryset of this model with the count of the rows of each category. The thing is, the way i know to do it, only categories present in the queryset are getting counted, but i want a queryset with all categories annotated with the count (0 if no rows with this category).

This is what im doing at the moment:

Model.objects.all().values('category').annotate(total=Count('category'))

Is there a way to display all categories, including such with count 0?

You can not count categories that do not exist, since, well... these do not exist. The choices are not even transferred to the database.

Using a CharField with choices is not the ideal modeling for this. Typically it is better to make a model Category and then another MyModel with ForeignKey [Django-doc] to link a MyModel object to a Category , so:

class Category(models.Model):
     = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class MyModel(models.Model):
    category = models.Category, on_delete=models.PROTECT

then we can create categories like:

Category.objects.bulk_create(
    Category(name='technology'),
    Category(name='art'),
    Category(name='science')
)

if we then link MyModel objects to these Category s, we can annotate the Category with the number of MyModel s with:

from django.db.models import Count

Category.objects.annotate(
    
)

Here the Category s that arise from this queryset will have an extra attribute .num_mymodel with the number of linked MyModel objects. Since a LEFT OUTER JOIN is performed, for Category s without any MyModel s, it will use 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