Why is django giving me an attribute error when I call _set.all() for its children models?

Posted by user1876508 on Stack Overflow See other posts from Stack Overflow or by user1876508
Published on 2013-06-28T18:15:16Z Indexed on 2013/06/29 4:21 UTC
Read the original article Hit count: 479

I have two models defined

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=144)

    @property
    def posts(self):
        self.Post_set.all()

class Post(models.Model):
    title = models.CharField(max_length=144)
    text = models.TextField()
    blog = models.ForeignKey('Blog')

but the problem is, when I run shell, and enter

>>> blog = Blog(title="My blog")
>>> post = Post(title="My first post", text="Here is the main text for my blog post", blog=blog)
>>> blog.posts

I get the error

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/lucas/Programming/Python/Django/djangorestfun/blog/models.py", line 9, in posts
    self.Post_set.all()
AttributeError: 'Blog' object has no attribute 'Post_set'
>>> 

Now I am having the following problem

>>> from blog.models import *
>>> blog = Blog(title="gewrhter")
>>> blog.save()
>>> blog.__dict__
{'_state': <django.db.models.base.ModelState object at 0x259be10>, 'id': 1, 'title': 'gewrhter'}
>>> blog._state.__dict__
{'adding': False, 'db': 'default'}
>>> post = Post(title="sdhxcvb", text="hdbfdgb", blog=blog)
>>> post.save()
>>> post.__dict__
{'blog_id': 1, 'title': 'sdhxcvb', 'text': 'hdbfdgb', '_blog_cache': <Blog: Blog object>, '_state': <django.db.models.base.ModelState object at 0x259bed0>, 'id': 1}
>>> blog.posts
>>> print blog.posts
None

Second update

So I followed your guide, but I am still getting nothing. In addition, blog.posts gives me an error.

>>> from blog.models import *
>>> blog = Blog(title="asdf")
>>> blog.save()
>>> post = Post(title="asdf", text="sdxcvb", blog=blog)
>>> post.save()
>>> blog.posts
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Blog' object has no attribute 'posts'
>>> print blog.all_posts
None

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models