我有點困惑於Django的行話。所以我有3個模型:Post,UserProfile(User),Favorite。收藏夾會跟蹤用戶收藏哪些帖子。Django查詢以獲取用戶最喜愛的帖子?
帖子--->收藏< ---用戶/用戶配置
最喜愛的模型:
class Favorite(models.Model):
user = models.ForeignKey(User, unique=False)
post = models.ForeignKey(Post, unique=False)
def __unicode__(self):
return self.user.username
用戶配置模式:
class UserProfile(models.Model) :
user = models.ForeignKey(User, unique=True)
def get_favorites(self):
if self.user:
return self.user.favorite_set.all()
在我post_list鑑於我通過所有帖子到我的模板,並在模板中我有一個for循環顯示所有職位。
{% for post in post_list %}
<hr/>
<div id=」post_{{ post.id }}」>
{% include 'posts/_post.html' %}
</div>
{% endfor %}
現在,在循環中,我想把一個邏輯,將顯示「收藏」!如果登錄的用戶已經收到郵件。我認爲傳統的SQL是這樣的:
SELECT favorite.post FROM favorite WHERE favorite.user = user.id
所以,在模板循環我可以做
{% if post in the.above.SQL.query%}Favorited!{% endif %}
現在我不能把這一對Django的行話出於某種原因。非常感謝您的幫助!
工作就像一個神奇魅力。我從來沒有使用ManyToMany,從來沒有過多關注它。現在我明白了!謝謝! – rabbid 2011-04-15 10:56:15