I have these models:
class BlogCategory(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
def get_number_of_categorys_items(self):
return self.post_set.count()
class Post(models.Model):
title = models.CharField(max_length=130)
content = models.TextField()
category = models.ForeignKey(BlogCategory, related_name='blog_category')
def __str__(self):
return self.title
And when I try to call method get_number_of_categorys_items
it cause error:
AttributeError: 'BlogCategory' object has no attribute 'post_set'
This method should return number of posts with this category.
What can I do?
Since you've specified the related_name
, Django would not automatically create the related name as post_set
for you. Either use:
def get_number_of_categorys_items(self):
return self.blog_category.count()
Or, don't specify the related_name
:
category = models.ForeignKey(BlogCategory)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With