A custom ordering SQL and Django models

33 views
Skip to first unread message

Daybreaker

unread,
Aug 4, 2009, 3:28:32 AM8/4/09
to Django users
I want to run a query like this:

select * from bbs_article a, bbs_article_tags a2, bbs_tag t where t.id
= a2.tag_id and a.id = a2.article_id order by (case when t.name =
'notice' then '' else t.name end)

which has a custom ordering rule.

As far as I know, Django model currently does not support such custom
orderings, but only field-based native orderings.

How do I use the above sql in most clear way (like using typical model
query with manually changed order clause), or is there any workaround
to do the same jobs?

Daniel Roseman

unread,
Aug 4, 2009, 4:56:00 AM8/4/09
to Django users

Daybreaker

unread,
Aug 4, 2009, 4:58:24 AM8/4/09
to Django users
Finally I implemented a custom manager.

http://dpaste.com/hold/75010/

But another problem arised, that Django's object_list generic view
only accepts a QuerySet object, not list neither other iterables.
Of course I can implement my own pagination with the given Paginator
class, but this seems not so much clean...

Daybreaker

unread,
Aug 4, 2009, 4:59:46 AM8/4/09
to Django users
I've tried that also, but it ALSO only accepts field names. Its
intention to be there is not to override previously set order clauses.
> might help.http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-sele...
> --
> DR.

krylatij

unread,
Aug 4, 2009, 10:25:08 AM8/4/09
to Django users
Use extra() method of query set with little hack ;)

mymodel.objects.extra(select={'ordering_field': 'IF(STRCMP
(bbs_tag.name, 'notice'), '',bbs_tag.name)'},
order_by=['ordering_field'])

Daybreaker

unread,
Aug 4, 2009, 9:21:44 PM8/4/09
to Django users
Thanks, that works! (but I already changed my implementation not to
use tag-based ordering...)
For more generality, you could replace bbs_tag with Tag._meta.db_table
value.
Reply all
Reply to author
Forward
0 new messages