如何在Django中按字段排序 [英] How to order by fields in Django

查看:81
本文介绍了如何在Django中按字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我来说,正确完成订单非常重要.我需要按索引对我的MonthlySpending对象进行排序.我已经尝试过从django模板获取dictsort,但无法正常工作.

For my case it will be very important to get the order right. I need to sort my MonthlySpending objects by its index. I have tried the dictsort from django template but does not work.

我也将排序包含在模型中,但是,该排序未在HTML中显示,但确实在管理员中显示.

I have also included the ordering in my models, however, the ordering is not shown in the HTML but it does show in the admin.

反正我可以按其索引对对象进行排序吗?

Are there anyways i can sort my objects by its index?

HTML

{% for month in object.monthlyspending_set.all|dictsort:"index" %}
    <tr class="yeardata ">
        <td>{{ month.name }}</td>
        <td>$ {{ month.monthly_income }}</td>
        <td>$ <a href="{% url 'finances:detail' month.slug %}">{{ month.target_savings }}</a></td>
        <td>$ {{ month.actual_savings }}</td>
        <td>{{ month.percentage_met }} %</td>
    </tr>
  {% endfor %}

Models.py

class MonthlySpending(models.Model):
    name = models.CharField(max_length=100)
    annualspending = models.ForeignKey(AnnualSpending, on_delete=models.CASCADE)
    index = models.IntegerField()
    slug = models.SlugField()
    objects = models.Manager

    class Meta:
        ordering = ['index']

推荐答案

我建议在传递查询集之前在查询集上使用 order_by .文档位于此处.您可以在视图中执行类似 some_query_set.order_by("index")的操作.

I recommend using order_by on your queryset before passing it down. Documentation is here. You can do something like some_query_set.order_by("index")in your views.

这篇关于如何在Django中按字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆