开发者

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:

  1. Subclass Django's ValuesQuerySet, name it for ex. OrderedValuesQueryset and change it's iterator method to use OrderedDict http://docs.python.org/dev/library/collections.html#collections.OrderedDict

  2. Create a Queryset subclass which in it's .values method returns an instance of your OrderedValuesQuerySet

  3. Create a custom models.Manager class which in it's get_query_set method uses your custom QuerySet from 2.
  4. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜