0

I need order a Queryset by date in desc order, but i need put in the end the objects at the end, I do this:

qs1 = Model.objects.exclude(date=None).order_by('-date')
qs2 = Model.objects.filter(date=None).order_by('-date')

and my list is:

l = list(qs1)+list(qs2)

There is a more efficiently way for this?

2 Answers 2

3
Model.objects.extra(select={'nodate':'ISNULL(date)'}, order_by=['nodate', '-date'])
Sign up to request clarification or add additional context in comments.

1 Comment

So then use 'date IS NULL' instead.
0

So, you're looking for all the objects that have a date ... and all the objects that don't have a date?

Wouldn't this work better:

Model.objects.order_by('-date)

Anyway, here's a good place to start ... read about Django filter chaining: http://docs.djangoproject.com/en/dev/topics/db/queries/#id1.

As a side note, isn't your query canceling itself out?

>>> d = MyModel.objects.filter(date=None).exclude(date=None).order_by('-date')
>>> d
[]
>>> d.query.get_compiler('default').as_sql()
('SELECT "date" FROM "table" WHERE ("table"."date" IS NULL AND NOT ("table"."date" IS NULL)) ORDER BY "table"."date" DESC', ())

I'm probably not understanding what you're asking...

1 Comment

The queries do seem to cancel each other out... unless it has something to do with grouping that I'm just not seeing. Looks like @diegueus might want the objects with no date at the end of the list, and maybe .order_by('-date') puts them at the beginning?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.