Home > Blockchain >  How to sort querysets from different models based on two fields?
How to sort querysets from different models based on two fields?

Time:02-03

I have querysets from different models which have only two fields in common: datetime and dt_created, and I would like to sort the objects first on datetime and then on dt_created, so that objects with the same datetime are sorted based on field dt_created.

How can I do that ?

Until now I was able to combine and sort the queryset with datetime like this:

lst_qs = list(qs_trades)   list(qs_deposits)   list(qs_withdrawals)
sorted_lst = sorted(lst_qs, key=lambda x: x.datetime)

CodePudding user response:

Is this what you wanted?

lst_qs = list(qs_trades)   list(qs_deposits)   list(qs_withdrawals)
sorted_lst = sorted(lst_qs, key=lambda x: (x.dt_created, x.datetime))

CodePudding user response:

You can use class Meta:

class Example(models.Model):
...
    class Meta:
        ordering = ['datetime', 'dt_created']
  • Related