queryset by custom field

52 views
Skip to first unread message

John M

unread,
May 22, 2007, 1:20:11 AM5/22/07
to Django users
Is it possible to order a queryset by a custom field?

I have several programmatic generated fields and need to sort the
display by them, is this possible?

Thanks

John

Malcolm Tredinnick

unread,
May 22, 2007, 2:17:32 AM5/22/07
to django...@googlegroups.com

The order_by fields are passed to the database and used in the SQL
statement, so you cannot use arbitrary fields there. You are restricted
to database columns (you can't even use computed values from those
columns).

I suspect a workaround is possible, though. All completely untested, but
it doesn't look that hard...

Create a subclass of QuerySet that overrides the __iter__ method. In
your version of __iter__, you call self._get_data(), sort the results
however you want and then return an iterator over the resulting
sequence.

To use this subclass in your models, create a custom manager on your
class that overrides the get_query_set() method of a normal manager.
Your custom method returns your QuerySet subclass, instead of the
QuerySet returned by the default get_query_set().

You can see the details of the default manager that you are going to
override in django.db.models.manager and QuerySet.__iter__ is in
django.db.models.query.

Details of creating a custom manager method are in
http://www.djangoproject.com/documentation/model-api/#custom-managers

Regards,
Malcolm

Reply all
Reply to author
Forward
0 new messages