2017-02-16 70 views
1

我想要獲取特定的Video對象,然後使用文檔中所述的ForeignKey反向查找來查找與其關聯的所有Rating對象。django反向查找foreignkey不工作

我有型號:

class Video(models.Model): 
... 
    rating_int = models.IntegerField(default=1, choices=CHOICES, name='rating_int') 
    def __str__(self): 
     return self.title 


class Rating(models.Model): 
    video = models.ForeignKey('Video', related_name='video', null=True) 

和看法:

def video_ratings(request): 
    vid_rate = Video.objects.get(pk=1) 
    ratings_of_video = vid_rate.rating_set.all() 
    context = { 
     'vid_rate': vid_rate, 'ratings_video': ratings_of_video 
    } 
    return HttpResponse(template.render(context, request)) 

當我試圖運行此我得到一個錯誤'Video' object has no attribute 'rating_set'

但是,當我讀Django文檔,它告訴我當你做反向查找時,你需要使用這個_set.all()命令。我不確定這裏缺少什麼。

回答

0

您在外鍵的loopkup中指定了related_name。所以rating_set現在不應該工作。

您可以查找喜歡

ratings_of_video = vid_rate.video.all() 

更好的命名慣例會在你related_name

class Rating(models.Model): 
    video = models.ForeignKey('Video', related_name='ratings', null=True) 

使用ratings然後查詢像

ratings_of_video = vid_rate.ratings.all() 
+0

唉唉,這是問題!沒有在文檔中看到,感謝您的提示 – ratrace123