python - Django 相关名称

标签 python mysql django

我正在尝试做类似的事情:

{% for property in current_listing %}
    {% for property_image in property.property_images.all %}

    {% endfor %}
{% endfor %}

但是我想要这样的东西:

{% for property in current_listing %}
    {% for property_image in property.property_images.**ORDER_BY('-order')[0]** %}

    {% endfor %}
{% endfor %}

我该怎么做?

最佳答案

如果我明白你想要什么,你可以试试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]

然后在模板上:

{% load my_tags %}

{% with image=property.property_images.all|get_first_ordered_by:'-order' %}
    {{ image }}
{% endwith %}

请注意,您不能使用 {% for %},因为 get_first_ordered_by 的结果不可迭代。

关于python - Django 相关名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13297690/

相关文章:

python - 使用新的初始迁移来压缩迁移

python - 如何对齐两个数字列表

python - 正则表达式查找两个模式并提取值

python - 如何迭代 Pandas 中的 MultiIndex 级别?

java - 使用 jcalender 时,我无法通过 MySQL 从 java 应用程序中按日期搜索?

python - Django 表单向导 : passing data between forms

python - Python中子列表的高效匹配

mysql - 如何插入选择...哪里不存在选择?

php - 使用 PHP 在 MYSQL 中存储图像路径

Python Django 查询集