Model:
class Person(models.Model):
friends= models.ManyToManyField("self", blank=True, null=True)
friends = person.friends.order_by('friends__id')[:5]
I tried also
friends = Person.objects.filter(friends=obj).order_by('-friends__id')[:5]
I need to get the friends ordered by the middle table id (pk).
Use intermediate table directly, and its no longer a queryset.
friends = [pf.to_person for pf in
person.friends.through.objects.filter(from_person=person)
.select_related('to_person')
.order_by('pk')]
Or you need to write raw SQL in ordering part.
person.friends.order_by(person.friends.through._meta.db_table+'.id')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With