[Answered ]-In Django, how do I order_by() when reaching across tables?

2👍

It’s not your order by that’s wrong but what you do with the results. Let us digest the following, particularly line 3

ordered_friends = Friendships.objects.filter(user__id=1).order_by('user__first_name')
for ordered_friend in ordered_friends:
    print ordered_friend.friend.first_name, ordered_friend.friend.last_name

In ordered_friend you have an instance of FriendShip each ordered_friend is returned to you in that ordered_friend‘s username. But having obtained an ordered_friend, you then do ordered_friend.friend but this is not the column that you orderd by so it’s not surprising that the items don’t get printed in alphabetical order. You porbably meant to do

print ordered_friend.user.first_name, ordered_friend.user.last_name

or did you perhaps intend to sort by friend in the first place?

Friendships.objects.filter(user__id=1).order_by('friend__first_name')
👤e4c5

Leave a comment