【问题标题】:Django query manytomanyfield in templateDjango在模板中查询manytomanyfield
【发布时间】:2012-07-04 11:43:21
【问题描述】:

如何在 Django 模板中查询多字段?

例如,这个 if 语句不起作用(我知道我不能在 Django 模板中调用带参数的函数),但这表明了我想做的事情:

模板.html

{% for post in posts %}
    {% if post.likes.filter(user=user) %}
        You like this post
    {% else %}
        <a>Click here to like this post</a>
    {% endif %}
{% endfor %}

models.py

class User(Model):
    # fields

class Post(Model):
    likes = ManyToManyField(User)

【问题讨论】:

  • 标准django模板系统不允许调用带参数的方法。如果想调用上面的代码,你可以使用 Jinja2。

标签: python django django-templates


【解决方案1】:

为了做您正在寻找的东西,您可以执行以下操作:

{% for post in posts %}
    {% if user in post.likes.distinct %}
        You like this post
    {% else %}
        <a>Click here to like this post</a>
    {% endif %}
{% endfor %}

或者,您可以使用 Greg 的方法。他的回答的优点是当你进入非常大的数据集时它会更好地扩展。这种方法不需要您编写任何自定义过滤器。

【讨论】:

    【解决方案2】:

    它不起作用,因为您似乎是在模板中编写 python 代码...您需要在视图中运行循环并将帖子列表及其信息传递给模板,或者编写模板过滤器这决定了某个用户是否喜欢某个帖子。例如:

    from django import template
    
    register = template.Library()
    
    @register.filter
    def is_liked_by(post, user):
        return bool(post.likes.filter(user=user))
    

    然后在你的模板中:

    {% for post in posts %}
        {% if post|is_liked_by:request.user %}
            You like this post
        {% else %}
            <a>Click here to like this post</a>
        {% endif %}
    {% endfor %}
    

    【讨论】:

    • 您可能需要考虑在查询集上使用.exists() 而不是bool(post.likes.filter(user=user))。它稍微快一点,这似乎是它的设计目的。它会像这样使用:return post.likes.filter(user=user).exists()
    猜你喜欢
    • 1970-01-01
    • 2019-09-20
    • 2019-08-07
    • 2014-11-22
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多