1

I have a join of two querysets:

fqs= FirstModel.objects.all()
sqs= SecondModel.objects.all()
sorted_qs = sorted(chain(fqs, sqs)) #<- need to sort here by "added" field. 

both models have this added field.

added = models.DateTimeField(auto_add_now=true)

but sorted_qs is giving me each time different order. I think, chain joins them randomly each time..

I need to sort by certain fieldname. how do i do this?

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

3

sorted needs to know the key:

sorted_qs = sorted(chain(fqs, sqs), key=lambda obj: obj.added)

see here: Using sorted() in Python

Community
  • 1
  • 1
Gabriel Amram
  • 2,700
  • 2
  • 19
  • 29