Inforian
Inforian

Reputation: 1736

Sort results fetched from models related with Foreign Key

I have two models related with Foreign Key and I want to sort the data alphabetically. I know I can fetch data of models related with foreign keys like :

follow = UserFollowers.objects.select_related('user').filter(follow = user_id)

Now this query fetched the data which I want but I want to sort the result based on first name which is stored in User table. Also If I run this query

follow = UserFollowers.objects.select_related('user').filter(follow = user_id).order_by('user')

then it sorts the result on the basis of user id but If I try this .order_by('user.<any other field>') then it gives me the error that you don't have choice of this field.

So Please tell how I can sort data of models related with foreign key. Thanks

Upvotes: 0

Views: 71

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You need to use the double-underscore syntax:

.order_by('user__username')

Upvotes: 1

Related Questions