In Django, how do I order_by() when reaching across tables?
<p>I'm trying to filter my Friendships objects and then order_by user.first_name, but it's not working. Can anyone tell me what I'm doing wrong?</p>

<p>Here's my models:</p>

<pre><code>class Friendships(models.Model):
    user = models.ForeignKey('Users', models.DO_NOTHING, related_name="usersfriend")
    friend = models.ForeignKey('Users', models.DO_NOTHING, related_name ="friendsfriend")
    created_at = models.DateTimeField(blank=True, null=True)
    updated_at = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'friendships'

class Users(models.Model):
    first_name = models.CharField(max_length=45, blank=True, null=True)
    last_name = models.CharField(max_length=45, blank=True, null=True)
    created_at = models.DateTimeField(blank=True, null=True)
    updated_at = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'users'
</code></pre>

<p>My query is as follows, which returns my needed Friendships, but the order is not correct. I've tried a number of different combinations and examples but just am not sure what I'm not correctly understanding:</p>

<p>My query in my controller:</p>

<pre><code>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
</code></pre>

<p>Note, I've tried a number of combinations in place of <code>user__first_name</code> and I know this is where I'm failing.</p>

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

<pre><code>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
</code></pre>

<p>In <code>ordered_friend</code> you have an instance of <code>FriendShip</code> each ordered_friend is returned to you in that <code>ordered_friend</code>'s username. But having obtained an <code>ordered_friend</code>, you then do <code>ordered_friend.friend</code> 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</p>

<pre><code>print ordered_friend.user.first_name, ordered_friend.user.last_name
</code></pre>

<p>or did you perhaps intend to sort by friend in the first place?</p>

<pre><code>Friendships.objects.filter(user__id=1).order_by('friend__first_name')
</code></pre>

python django orm