How to sort column fields in Django model.object.values()
I am 开发者_开发百科using this
objects = Model.objects.values('var1', 'var2', 'var4')
IN template i use
{% for fieldname in object.keys %}<th>{{ fieldname }}</th>{% endfor %}
But the field names appear in arbitrary order like
var4---var1----var2
I want them to appear like i provided in function
var1---var2----var4
is this possible
The easiest solution is to just use values_list
, which returns tuples and change your template accordingly.
https://docs.djangoproject.com/en/1.3/ref/models/querysets/#django.db.models.query.QuerySet.values_list
If for whatever reason, you want to keep using dict-s, and want an "automagical" solution, you'd have to do quite a bit of work:
Subclass Django's
ValuesQuerySet
, name it for ex.OrderedValuesQueryset
and change it'siterator
method to useOrderedDict
http://docs.python.org/dev/library/collections.html#collections.OrderedDictCreate a
Queryset
subclass which in it's.values
method returns an instance of yourOrderedValuesQuerySet
- Create a custom
models.Manager
class which in it'sget_query_set
method uses your customQuerySet
from 2. - Set the custom Manager to be used in your model. See https://docs.djangoproject.com/en/1.3/topics/db/managers/#custom-managers
Now what you are trying to do will work automatically on that model. You can also set the custom manager to a different attribute than objects
, to also keep the default manager available.
The question is rather how to sort a Python dictionary, because this is what values()
returns. Python dictionaries by definition do not have an ordering.
See this blog post
精彩评论