2017-03-21 68 views
0

我有兩個車型之一是如何從外鍵約束檢索django模型的值?

class NewsLikes(models.Model): 
id = models.IntegerField(db_column="id", max_length=11, help_text="") 
userId = models.ForeignKey(Users, db_column='userId', max_length=11, help_text="") 
newsId = models.ForeignKey(NewsMappings, db_column='newsMappingId', max_length=11, help_text="") 
createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text=" 

,另一個模式是

class NewsMappings(models.Model): 
    id = models.IntegerField(db_column="id", max_length=11, help_text="") 
    newsId = models.ForeignKey(News, db_column='newsId', max_length=11, help_text="") 
    boardId = models.ForeignKey(Boards, db_column='boardId', max_length=11, help_text="") 
    isWallPost = models.BooleanField(db_column="isWallPost", default=False, help_text="") 

模型消息像包含消息映射的外鍵。我在我的django模板中傳遞新聞映射作爲上下文,我想要統計新聞映射中存在多少新聞喜歡ID並將其顯示在模板上。

回答

0

有一個django文檔Many to one 它有關係映射的外鍵解釋。在你的情況下,如果你正在尋找獲得每個NewsLikeID的所有NewsMappings列表然後檢查像下面的東西

NewsLikes.objects.filter(NewsMapping__newsId='SomeNewsID')