Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django manytomany self relation order by the middle table id

Tags:

django

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).

like image 811
kamel Avatar asked Apr 26 '12 10:04

kamel


1 Answers

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')
like image 186
okm Avatar answered Oct 11 '22 20:10

okm