简体   繁体   English

如何在 Django 查询集中使用 order_by?

[英]How to use order_by in Django queryset?

I apply order_by to a queryset and the results are mixed up.我将 order_by 应用于查询集,结果混淆了。 Is there any difference if I apply it to a queryset?如果我将它应用于查询集有什么区别吗?

The table has three columns: Name Age Description Here is the code:该表包含三列: 名称 年龄 描述 这是代码:

Query = table1.objects.filter(Name__iexact='Nico').order_by('Age').distinct()
ages = Query.values_list('Age')
descr= Query.values_list('Description')

Here only Age is sorted correctly.这里只有 Age 被正确排序。 The match between these Age and Description is distorted.这些年龄和描述之间的匹配被扭曲了。 What is wrong here?这里有什么问题?

What is wrong ?怎么了 ? Well, actually, the design itself.嗯,实际上,设计本身。 "Parallel lists" - two lists (or similar types) matched on position - is an antipattern. “并行列表” - 两个列表(或类似类型)在位置上匹配 - 是一种反模式。 It's bulky, harder to use (you have to keep track of indexes and subscript the two lists), and brittle (if anything changes one of the lists for whatever reason, the data are not matched anymore).它体积庞大,难以使用(您必须跟踪索引并为两个列表添加下标),而且很脆弱(如果出于某种原因更改了其中一个列表,则数据不再匹配)。

If you need to keep both informations matched, keep them in a single list (or here queryset) as tuples (here query.values_list("Age", "Description") ) or dicts (here query.values("Age", "Description")) .如果您需要保持两个信息匹配,请将它们作为元组(此处为query.values_list("Age", "Description") )或字典(此处为query.values("Age", "Description")) This will make your code simpler and safer.这将使您的代码更简单、更安全。

NB: I of course assume you want to match those two querysets given your mention that "The match between these Age and Description is distorted".注意:我当然假设您想匹配这两个查询集,因为您提到“这些年龄和描述之间的匹配被扭曲了”。

Try to have your order_by on the end after distinct.尝试在distinct之后将您的order_by放在最后。

Either that or try要么尝试

Query = table1.objects.filter(Name__iexact='Nico').distinct()

Query = Query.order_by('Age')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM