我有两个表,document 和 publishermatter
在publishermatter 中,我有一列FK_doc,它是document 表的外键。
对于一个文档,publishermatter 表中有零行或多行。
我正在将文档对象传递给 Django 模板,并且我希望与具有特定条件的 publishermatter 行,其中 key(列名)等于 PAGECSS(值(value))
我正在按照以下方式做。
代码 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>
另一种方法是通过执行以下操作将 publishermatter 从 View 中传递
doc_obj.publishermatter_set.get(key='PAGECSS')
但我想在模板中执行此操作,因为我正在从 View 中传递文档对象。
在Django1.4 中有什么方法可以过滤Django 模板上的查询吗?
最佳答案
您确实可以使用自定义模板过滤器来做到这一点,但恕我直言,这不是正确的设计,因为它在不应该知道的地方公开了模型实现细节。
这里更好的解决方案是将适当的方法添加到您的模型类中:
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)公开为模板层的一部分,您当然可以使用自定义模板过滤器。假设您的应用程序 ( 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>
哦,是的,正如 Daniel Roseman 正确提到的:Django 1.4 早已过时、无人维护、无人支持且不安全。我知道这可能不仅仅取决于您,但您应该确实尽快切换到受支持的最新版本。
关于python - 如何在 Django 模板中使用过滤器或获取方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094868/