StopIteration404 StopIteration404 - 3 months ago 29
Python Question

Get models ordered by an attribute that belongs to its OneToOne model

Let's say there is one model named

User
and the other named
Pet
which has a
OneToOne
relationship with
User
, the
Pet
model has an attribute
age
, how to get the ten
User
that owns the top ten
oldest
dog?

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

class Pet(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
owner = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.IntegerField(null=False)





In
User
, there is an attribute
friends
that has a
ManyToMany
relationship with
User
, how to get the ten
friends
of
User Tom
that owns the top ten
oldest
dog?

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

class Pet(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
owner = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.IntegerField(null=False)

Answer

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]