2015-06-29 98 views
0

我目前在我的Django應用程序中設置了兩個具有ForeignKey關係的模型。無法訪問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.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將輸出Cat查詢每個模型各自titlename。但是如果我做p.commentp.comment_id,則會出現錯誤。與任何Comment對象一樣。但是當我做print c.post,我得到None。我是什麼,以便使p.<field_here>" = Dog`失蹤?

+0

https://docs.djangoproject.com/en/1.8/topics/db/queries/ – NightShadeQueen

+0

我沒有看到從我沒相比有什麼Django的文檔顯示的差異。 – tear728

回答

0

既然你有相關的名字「意見」,訪問來自Post設定國外模式應該被稱爲是這樣的:

p.comments 

但是,因爲你可以有很多意見爲同一職位,這將不會返回一個獨特的價值,但你需要查詢的相關經理。所以,你可以得到:

p.comments.filter(name="Dog") 
+0

謝謝!這工作完美。 – tear728