Apostolos
Apostolos

Reputation: 8101

Order a django queryset by 2 criteria

I have a django model that has two fields among others

class Entry(models.Model):
    #other fields
    date = models.DateField()
    user = models.ForeignKey(User)

I want to retrie all user models order them by user alphabetically and then order them by date ascending. Will this do?

entries = Entry.objects.all().order_by('user').order_by('date')

But I don't think this is the case. The result of the above command is entries ordered_by date but not by user (cause the order_by('date') was called last in the chain). Correct? How can I order a queryset using to criteria?

Upvotes: 1

Views: 285

Answers (1)

Bogdan Iulian Bursuc
Bogdan Iulian Bursuc

Reputation: 2275

If you want users alphabetically you must sort by user name not id, like:

Entry.objects.order_by('user__first_name', 'date')

Upvotes: 4

Related Questions