ORM排序与模型“元"的比较订购-Django 1.11 [英] ORM ordering vs Model "Meta" ordering - Django 1.11

查看:36
本文介绍了ORM排序与模型“元"的比较订购-Django 1.11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小问题-订购商品的更好方法是什么:
1)

Small question - what is better way for ordering items:
1)

class Table(models.Model):
    ...
    class Meta:
        ordering = ['user']

2) Table.objects.all().order_by("user")

我认为第二个更好,因为cuz首先总是会返回有序查询集,如果有时我们不需要订单,这会花费额外的时间吗?是否还有其他理由使用1种方法,每次都方便地不写" .order_by("user")?

推荐答案

在基于类的视图中使用模型时,使用第一个选项有时很重要,因为它可能是作为传递的模型ForeignKey .在这种情况下,如果未在 Meta 中添加 ordering ,则无法在模板中引用它.

When you are using the model in a class-based view it is sometimes important to use the first option because it might be a model passed as a ForeignKey. In this case when referencing it within your template you cannot set the order if you have not added the ordering in Meta.

这篇关于ORM排序与模型“元"的比较订购-Django 1.11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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