问题
I am making a blog app using django...
This is my model.py
class categories(models.Model):
Title = models.CharField(max_length=40)
class Blog(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
Date = models.DateTimeField(default=datetime.now)
Blog_title = models.CharField(max_length=255)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='likes',blank=True)
Description = RichTextUploadingField(blank=True, null=True,config_name='special')
Blog_image = models.ImageField(upload_to='blog_image', null=True, blank=True)
Category = models.ForeignKey(categories,on_delete=models.CASCADE,related_name='Categories')
I was wondering How to count the total no of blog present under a particular category?
I want to track a specific count rate for all Categories...
回答1:
If you want to count the number of Blogs per Category, we can make an annotation on the Category:
from django.db.models import Count
Category.objects.annotate(
num_blogs=Count('Categories')
)
But (as specified later), using categories as related name is downright wrong, and should be renamed to blogs since this is the reverse relation, in that case the query is:
from django.db.models import Count
Category.objects.annotate(
num_blogs=Count('blogs')
)
The result is a QuerySet containing all the Category objects, and each Category object, will have an attribute num_blogs that contains the number of blogs related to this category.
The advantage of doing this by annotations is that you avoid the "N+1 problem": here we still perform one query, and not one query for the categories, and n queries to obtain the blog count for that specific category. In MySQL the query will look like:
SELECT category.*, COUNT(blog.id)
FROM category
LEFT OUTER JOIN blog ON blog.category_id = category.id
GROUP BY category.id
Note: typically attributes in Python start wit a lowercase (and use underscores between words), so
blog_title, andcategoryinstead ofBlog_titleandCategory
Note: the
related_nameis the name you give the objects of the reverse relation, so therelated_nameof thecategory = ForeignKey(..)should be'blogs', not'categories'.
回答2:
for title in categories.objects.all():
Blog.objects.filter(Category__Title=a.title).count()
This would do what you are looking for.
回答3:
[{"category_title":category.Title, "count":Blog.objects.filter(Category=category).count()} for category in categories.objects.all()]
This will give a list of dictionaries with the category title and its corresponding counts
回答4:
you can do with Category model also.
Categories.objects.filter(Title="someName").Categories.all().count()
来源:https://stackoverflow.com/questions/52418944/how-to-count-items-in-a-foreign-key