如何在Django模板中使用filter或get方法?

时间:2017-11-03 11:36:53

标签: python django

我有两个表,文档 publishermatter

publishermatter 中,我有一列 FK_doc ,它是文档表的外键。

对于一个文档, publishermatter 表中有零行或多行。

我正在将文档对象传递给 Django模板,并且我希望来自publishermatter的行具有特定条件,其中(列名)等于 PAGECSS < /强>(值)

我是按照以下方式做的。

代码01

<div class="col-sm-7">
    {% for item in document.publishermatter_set.key %}
        {% if item.key == 'PAGECSS' %} 
            <p><br/>{{ item.key }} - {{ item.value }}</p>
        {% endif %}
    {% endfor %}
</div>

其他方法是通过执行以下操作从视图中传递发布者

doc_obj.publishermatter_set.get(key='PAGECSS')

但我想在Template中执行此操作,因为我从视图传递文档对象。

Django1.4中是否有任何方法可以过滤Django模板上的查询?

1 个答案:

答案 0 :(得分:4)

你确实可以使用自定义模板过滤器来做到这一点,但这不是正确的设计恕我直言,因为它在不应该知道的地方公开模型实现细节。

这里更好的解决方案是将正确的方法添加到模型类中:

class Document(models.Model):
    # your code here...

    # NB : may not be the best naming but I don't have enough
    # context to think of something better...
    def get_pagecss(self):
        # NB : only use `.get(...) if you have a unique 
        # constraint on (document, key) in Publishmatter
        # - else you want to use `filter(...)` and adapt
        # your template code to work on a queryset instead
        try:  
            return self.publishermatter_set.get(key="PAGECSS")
        except Publishmatter.DoesNotExist:
            return None # or anything that makes sense

然后在你的模板中:

  <div class="col-sm-7">
    {% with document.get_pagecss as item %}
      {% if item%} 
        <p><br/>{{ item.key }} - {{ item.value }}</p>
      {% endif %}
    {% endwith %}
  </div>

如果确实希望公开实际细节(AFAICT没有更多上下文)作为模板层的一部分,您当然可以使用自定义模板过滤器。假设您的应用已经有了一些templatags文件(if not just check the doc),您的过滤器可能如下所示:

@register.filter
def publishmatter_get(obj, key):
    try:
        return obj.publishmatter_set.get(key=key)
    except Publishmatter.DoesNotExist:
        return None # etc...

并在您的模板中:

  <div class="col-sm-7">
    {% with document|publishmatter_get:"PAGECSS" as item %}
      {% if item%} 
        <p><br/>{{ item.key }} - {{ item.value }}</p>
      {% endif %}
    {% endwith %}
  </div>

哦,是的,正如丹尼尔罗斯曼正确提到的那样:Django 1.4已经死了,没有维护,没有支持和不安全。我知道这可能不仅仅取决于您,但您应该真的尽快切换到最近支持的版本。