Opened 15 years ago

Closed 15 years ago

#12549 closed (invalid)

Native list method sort() does not work on ValuesListQuerySet instance returned from value_list() QuerySet

Reported by: jonathan_livni Owned by: nobody
Component: Core (Other) Version: 1.1-beta
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The following code causes an exception:

    members = Member.objects.all().values_list('name',flat=True)
    members.sort(key=len,reverse=True)  # Sorts members so that longer strings are first

The exception is:

   Traceback (most recent call last):
     File "members_update.py", line 1179, in <module>
    uploadMembers(trace,mems.members,configuration=conf)
     File "/usr/lib/python2.5/site-packages/django/db/transaction.py", line 265, in _commit_manually
    return func(*args, **kw)
     File "members_update.py", line 186, in uploadProducts
    members.sort(key=len,reverse=True)  # Sorts members so that longer strings are first
   AttributeError: 'ValuesListQuerySet' object has no attribute 'sort'

As far as the documentation goes, value_list() QuerySet was supposed to return a List object, not a ValuesListQuerySet. The documentation specifically states that value_list does is one of the functions not returning a QuerySet. Even if there's some kind of need to to return a List object, at least you would expect it to behave like a List object and support its methods - such as sort()

Change History (1)

comment:1 by Luke Plant, 15 years ago

Resolution: invalid
Status: newclosed

On the contrary, the only documentation I can find (1.0, 1.1, trunk) explicitly states that values_list() is one of the functions that does return a QuerySet. It also says:

 values(*fields)
 ---------------
 Returns a ValuesQuerySet -- a QuerySet that evaluates to a list of
 dictionaries instead of model-instance objects.
 
 ...

 values_list(*fields)
 --------------------
 This is similar to values() except that instead of returning a list 
 of dictionaries, it returns a list of tuples.

In practice, the lazy nature of QuerySets and the fact that they represent database queries means that it would be a bad idea for them to support any of the list methods that mutate the contents of the list.

Note: See TracTickets for help on using tickets.
Back to Top