我定义了两个模型
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')
但问题是,当我运行shell时,输入
>>> 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
我收到错误
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'
>>>
现在我遇到以下问题
>>> 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
所以我跟着你的导游,但我仍然一无所获。另外,blog.posts给我一个错误。
>>> 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
答案 0 :(得分:3)
post_set
应为小写:
self.post_set.all()
<强>更新强>
事实证明,您确实可以在名为Blog
的{{1}}上创建一个属性,并让它返回一个博客帖子的列表:
posts
class Blog(models.Model):
title = models.CharField(max_length=144)
@property
def posts(self):
return self.post_set.all() # note the `return`
现在实际上是blog.posts
的别名。因此,以下查找现在将起作用:
blog.post_set.all()
最后,要获取每个对象的字典值列表,您可以按以下方式操作from main.models import *
blog = Blog(title="asdf")
blog.save()
post = Post(title="asdf", text="sdxcvb", blog=blog)
post.save()
blog.posts # returns [<Post: Post object>]
blog.post_set.all() # returns [<Post: Post object>]
:
blog.posts
答案 1 :(得分:0)
或更好,请使用related_name:
class Post(models.Model):
title = models.CharField(max_length=144)
text = models.TextField()
blog = models.ForeignKey('Blog', related_name="posts")
你可以这样做:
from main.models import *
post = Post(title="asdf", text="sdxcvb", blog=blog)
post.posts.create("asdf") #Create it "inline"
blog = Blog(title="another_asdf")
post.posts.add(blog) #Added it (don't need call save method!)
blog.posts.all() # returns [<Post: Post object>]
然后使用value方法
blog.posts.values()
# [{'id': 1, 'tile': 'asdf', 'text': 'sdxcvb', 'blog': 'THE_BLOG_ID'}]
希望有所帮助!