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]
- [Django]-Can't get proper response from `issubclass()` when called with Django's `__fake__` model type inside migration
- [Django]-Django Rest Framework: Respond with 404 if no result found
- [Django]-Using variable instead of field name in Django query comparions
- [Django]-Is apache necessary while we have python's built-in SimpleHttpServer
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.
- [Django]-Django workflow to convert model superclass to subclass
- [Django]-What is a distributed messaging system? Specifically what is 'distributed' in it?
- [Django]-Difference between returning modified class and using type()
Source:stackexchange.com