[Django]-Get models ordered by an attribute that belongs to its OneToOne model

7👍

Use the double-underscore syntax.

User.objects.order_by('-pet__age')[:10]

Edit

To get the ten friends of Tom, you can get the instance and filter:

User.objects.get(name='Tom').friends.order_by('-pet__age')[:10]

or if you already have Tom:

tom.friends.order_by('-pet__age')[:10]

0👍

Try this :
First define unicode in model User like this:
By this,User model objects will always return name field of the user records.

 class User(models.Model):
    name = models.CharField(max_length=50, null=False, blank=False)
    friends = models.ManyToManyField(self, ...)

    def __unicode__(self):
       return self.name

Then use this query:

   User.objects.filter(friends='Tom').order_by('-pet__age')[:10]

0👍

Another solution (alternative to order_by) is using nlargest function of heapq module, this might be better if you already have friends list (tom’s friends in this case) with a large number of items (I mean from performance perspective).

import heapq

heapq.nlargest(
    10,
    User.objects.get(name='Tom').friends.all(),
    key=lambda f: f.pet.age
)

Note: You have also nsmallest function that you can use to get the youngest pets.

Leave a comment