How can I sort by id of ManyToManyField in Django?

I have ManyToManyField in a user object and it is used to map the users that the user is executing. I am trying to show a list of subsets of those they recently used. Is there a trick in .order_by () that will allow me to sort by ManyToManyField ID? There is data, right?

# (people the user is following)
following = models.ManyToManyField(User, related_name="following", blank=True)

theuser.following.filter(user__is_active=True).order_by("user__id")

This will give me a list of users followed by the user, but ordered when they joined. I want the order of the next list to be in order when the user followed them.

+5
source share
4 answers

, . extra, . :

theuser.following.filter(user__is_active=True)\
    .extra(select={'creation_seq': 'appname_user_user_following.id'})\
    .order_by("creation_seq")

, appname_user_user_following - , Django . - -, .

SQL, :

SELECT (appname_user_user_following.id) AS `creation_seq`, `appname_user`.`id`
FROM `appname_user` INNER JOIN `appname_user_user_following` ON
(`appname_user`.`id` = `appname_user_user_following`.`user_id`) WHERE
`appname_user_user_following`.`user_followed_id` = 1  ORDER BY `creation_seq` ASC';
+2

( , Django 1.10) extra, . , ".id" order_by. .

pizza.toppings.all().order_by('appname_pizza_toppings.id')

article.tags.all().order_by('appname_article_tags.id')

:

theuser.following.filter(user__is_active=True)\ .order_by("appname_user_user_following.id")

, , .

+1

Django 1.11.10.

( ?).

, @Ry4an Brase

recently_followed = '-{}.id'.format(theuser.following.through._meta.db_table)  
theuser.following.filter(user__is_active=True).order_by(recently_followed)
+1

, ManytoManyField. .

nb: !

class Person(models.Model)
    name = models.CharField(max_length=30)

class FollowerRelationship(models.Model)
    follower = models.ForeignKey(Person, related_name = following_set)
    following = models.ForeignKey(Person, related_name = follower_set)

.

# Create Person objects
>>> a = Person(name="Alice")
>>> a.save()
>>> b = Person(name="Bob")
>>> b.save()
>>> c = Person(name="Chris")
>>> c.save()

# Let Alice follow Chris and Bob 
>>> FollowerRelationship.objects.create(follower=a, following=c)
>>> FollowerRelationship.objects.create(follower=a, following=b)

FollowerRelationship, , , :

>>> qs = FollowerRelationship.objects.filter(follower=a).order_by('id')
>>> [fr.following for fr in qs]

, FollowerRelationship, "follow" Person .

" " Django, , "--".

0

All Articles