How can I sort by the id of a ManyToManyField in Django?

后端 未结 4 748
猫巷女王i
猫巷女王i 2020-12-19 01:16

I\'ve got a ManyToManyField in a user object and it\'s used to map the users that user is following. I\'m trying to show a subset list of who they have most recently followe

4条回答
  •  萌比男神i
    2020-12-19 02:04

    I just found a way to do this without having to create a class for the relationship. It relies on the extra feature that lets you add additional columns to output. In your example it would look like:

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

    Notice that appname_user_user_following is the name of the relationship table Django creates under the covers. It's deterministic and something you can get and set via meta-mechanisms, but it's pretty much safe to hardcode.

    Here's an example of the SQL that's being created under the covers with fake table and columns names:

    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';
    

提交回复
热议问题