rab*_*bid 4 django django-templates django-models
我对Django的术语感到有些困惑.所以我有3个型号:Post,UserProfile(User),Favorite.收藏夹会跟踪用户收藏的帖子.
交--->收藏<---用户/用户配置
喜欢的型号:
class Favorite(models.Model):
user = models.ForeignKey(User, unique=False)
post = models.ForeignKey(Post, unique=False)
def __unicode__(self):
return self.user.username
Run Code Online (Sandbox Code Playgroud)
UserProfile模型:
class UserProfile(models.Model) :
user = models.ForeignKey(User, unique=True)
def get_favorites(self):
if self.user:
return self.user.favorite_set.all()
Run Code Online (Sandbox Code Playgroud)
在我的post_list视图中,我将所有帖子传递给我的模板,在模板中我有一个显示所有帖子的for循环.
{% for post in post_list %}
<hr/>
<div id=”post_{{ post.id }}”>
{% include 'posts/_post.html' %}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
现在在for循环中我想放一个显示"收藏!"的逻辑.如果已登录的用户已收藏帖子.我认为传统的SQL是这样的:
SELECT favorite.post FROM favorite WHERE favorite.user = user.id
Run Code Online (Sandbox Code Playgroud)
所以在模板循环中我可以做到
{% if post in the.above.SQL.query%}Favorited!{% endif %}
Run Code Online (Sandbox Code Playgroud)
现在我出于某种原因无法将其翻译成Django lingo.非常感谢您的帮助!
Dan*_*man 14
要认识到的是,您的Favorite模型实际上是Post和User之间多对多关系的直表.如果你在某处声明一个ManyToManyField,Django实际上可以自动管理它.就个人而言,我会在UserProfile上这样做 - 所以这个关系实际上变成Post和UserProfile之间的关系:
class UserProfile(models.Model):
favorites = models.ManyToManyField(Post, related_name='favorited_by')
Run Code Online (Sandbox Code Playgroud)
现在你不需要你的get_favorites方法,因为它可以通过userprofile.favorites.all().你可以在模板中使用它原样:
{% if post in userprofile.favorites.all %}Favorited!{% endif %}
Run Code Online (Sandbox Code Playgroud)
但这最终会导致效率极低,因为您将对帖子列表中的每个帖子执行相同的相同查询.因此,{% with %}在循环之前使用标记获取收藏夹:
{% with userprofile.favorites.all as favorite_posts %}
{% for post in post_list %}
{% if post in favorite_posts %}Favorited{% endif %}
...
{% endfor %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3023 次 |
| 最近记录: |