【问题标题】:Django query to get User's favorite posts?Django 查询以获取用户最喜欢的帖子?
【发布时间】:2011-08-06 04:59:05
【问题描述】:

我对 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

UserProfile 模型:

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 %}

现在,在那个 for 循环中,我想添加一个显示“收藏!”的逻辑。如果登录用户收藏了帖子。我认为常规的 SQL 是这样的:

SELECT favorite.post FROM favorite WHERE favorite.user = user.id

这样我就可以在模板循环中做

{% if post in the.above.SQL.query%}Favorited!{% endif %}

现在由于某种原因,我无法将其翻译成 Django 术语。非常感谢您的帮助!

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    要认识到的是,您的 Favorite 模型实际上是 Post 和 User 之间多对多关系的直通表。如果您在某处声明 ManyToManyField,Django 实际上可以自动管理它。就个人而言,我会在 UserProfile 上这样做 - 所以关系实际上变成了 Post 和 UserProfile 之间的关系:

    class UserProfile(models.Model):
        favorites = models.ManyToManyField(Post, related_name='favorited_by')
    

    现在您不需要get_favorites 方法,因为它可以通过userprofile.favorites.all() 获得。您可以在模板中按原样使用:

    {% if post in userprofile.favorites.all %}Favorited!{% endif %}
    

    但这最终会变得非常低效,因为您将对帖子列表中的每个帖子执行相同的查询。所以,在循环之前使用{% with %}标签获取收藏夹一次:

    {% with userprofile.favorites.all as favorite_posts %}
      {% for post in post_list %}
        {% if post in favorite_posts %}Favorited{% endif %}
        ...
      {% endfor %}
    {% endwith %}
    

    【讨论】:

    • 就像一个神奇的魅力。我从来没有使用过ManyToMany,从来没有关注过它。现在我明白了!谢谢!
    【解决方案2】:

    虽然丹尼尔说得很好,但我会发布您想要的查询:)

    Post.objects.filter(favorite__user=user)
    

    【讨论】:

    • 有人可以将 django 文档指向这样的用法。我以为你只能从表外键开始跨表移动?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2020-12-12
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2020-11-04
    相关资源
    最近更新 更多