【问题标题】:Filter foreign key objects in django template在 django 模板中过滤外键对象
【发布时间】:2021-11-17 06:51:18
【问题描述】:

我有以下模型用于“存档”帖子(即,如果它是由用户为帖子创建的,则该帖子现在对该用户隐藏)

models.py

class ArchivedFlag(models.Model):
    group = models.ForeignKey(Group,
                             on_delete=models.CASCADE,
                             related_name='archived_commits')
    post = models.ForeignKey(Commit,
                             on_delete=models.CASCADE,
                             related_name='archived_flag')
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             related_name='archives')

在一个特定的模板中,我想要基于当前用户组和正在检查的当前帖子是否存在 ArchivedFlag 的逻辑。

模板.html

{% for p in posts %}

<form action="{% url 'archive_posts' p.oid %}" method="post">
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ request.get_full_path }}">

    {% if <...an archived flag exists with post==post and group==user.group...> %}
        <...Do stuff for archived post...>
        <button type="submit", name="p_oid", value="{{ p.oid }}", class="btn btn-primary btn-sm">Restore</button>
    {% else %}
        <...do stuff for unarchived post...>
        <button type="submit", name="p_oid", value="{{ p.oid }}", class="btn btn-primary btn-sm">Archive</button>
    {% endif %}

</form>
{% endfor %}

有没有办法在 django 模板中做到这一点?我在模板中找不到任何关于过滤的信息,所以这可能是不可能的。

【问题讨论】:

    标签: html django django-views django-templates django-template-filters


    【解决方案1】:

    您不能在 Django 模板中过滤/查询。

    但是,如果你给你的提交模型一个属性模型方法,比如 is_archived,你可以在条件中使用它。

    模型方法的文档在这里:https://docs.djangoproject.com/en/3.2/topics/db/models/#model-methods

    因此,您的 Commit 模型可以有一个返回布尔值的属性,如下所示:

    @property
    def is_archived(self):
        return <however you know it's archived>
    

    然后你可以像这样使用你在问题中的模式:

    {%for post in posts %}
      {% if post.is_archived %}
        do a thing
      {% else %}
        do a different thing
      {% endif %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 2021-06-06
      • 2013-09-23
      • 1970-01-01
      • 2015-09-10
      • 2022-06-25
      • 2018-02-03
      • 2014-01-08
      • 2018-04-12
      相关资源
      最近更新 更多