[英]Django related_name
I'm trying to do something like: 我正在尝试做类似的事情:
{% for property in current_listing %}
{% for property_image in property.property_images.all %}
{% endfor %}
{% endfor %}
But I would like something like: 但是我想要这样的东西:
{% for property in current_listing %}
{% for property_image in property.property_images.**ORDER_BY('-order')[0]** %}
{% endfor %}
{% endfor %}
How can I do this? 我怎样才能做到这一点?
If I understand what you want, you can try custom template filter : 如果我了解您想要的内容,可以尝试使用自定义模板过滤器 :
from django import template
register = template.Library()
@register.filter
def get_first_ordered_by(queryset, order):
return queryset.order_by(order)[0]
Then on a template: 然后在模板上:
{% load my_tags %}
{% with image=property.property_images.all|get_first_ordered_by:'-order' %}
{{ image }}
{% endwith %}
Note, that you can not use {% for %} since result of get_first_ordered_by
is not iterable. 注意,您不能使用{%for%},因为
get_first_ordered_by
结果不可迭代。
您可以在Model的类定义中添加一个方法,以返回所需的查询,然后从您的模板中取消该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.