diegueus9
diegueus9

Reputation: 31532

How can join two django querysets in one?

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?

Upvotes: 0

Views: 1026

Answers (2)

Jason Leveille
Jason Leveille

Reputation: 1190

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...

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

Model.objects.extra(select={'nodate':'ISNULL(date)'}, order_by=['nodate', '-date'])

Upvotes: 3

Related Questions