Python 访问外国关键元素时遇到问题
目前,我在Django应用程序中设置了两个具有ForeignKey关系的模型Python 访问外国关键元素时遇到问题,python,django,Python,Django,目前,我在Django应用程序中设置了两个具有ForeignKey关系的模型 class Post(models.Model): title = models.CharField(max_length=100) body = RichTextField(config_name='awesome_ckeditor') pub_date = models.DateTimeField('date', null=True) description = models.Cha
class Post(models.Model):
title = models.CharField(max_length=100)
body = RichTextField(config_name='awesome_ckeditor')
pub_date = models.DateTimeField('date', null=True)
description = models.CharField(max_length=100, blank=True, null=True)
photo = models.ImageField(upload_to='media/', blank=True, null=True)
def __unicode__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", blank=True, null=True)
name = models.CharField(max_length=100, null=True)
comment = models.TextField(blank=True)
pub_date = models.DateField("date", blank=True, null=True)
def __unicode__(self):
return unicode(self.name)
我没有得到的是在两者之间提出疑问。我尝试过通过shell进行查询,但没有成功。如果我设置了
Post(title=“Cat”)
,然后进行c=Comment(name=“Dog”)
,我可以通过p=Post.object.get(pk=1)
和p.title
这样的方式查询每个模型各自的title
或name
。但是如果我做了p.comment
或p.comment\u id
,就会出现错误。与任何注释对象类似。然而,当我打印c.post时,我得到了无。为了使p.“=
Dog`?”我缺少什么?由于您有相关的名称“comments”,因此从Post
访问设置外部模型的权限应按以下方式调用:
p.comments
但是,由于同一篇文章可以有许多评论,因此这不会返回唯一的值,而是返回一个需要查询的相关经理。因此,您可以获得:
p.comments.filter(name="Dog")
与Django文档显示的内容相比,我看不出有什么不同。