简体   繁体   中英

How to use order_by in Django queryset?

I apply order_by to a queryset and the results are mixed up. 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. 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")) . 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.

Either that or try

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

Query = Query.order_by('Age')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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