Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object has no attribute _set', Django

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?

like image 674
Q-bart Avatar asked Dec 24 '15 05:12

Q-bart


1 Answers

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)
like image 151
alecxe Avatar answered Sep 22 '22 17:09

alecxe