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

后端 未结 4 744
猫巷女王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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 02:01

    Tested with Django 1.11.10.

    You don't have to hardcode the relationship table name (How to read the database table name of a Model instance?).

    So an update on @Ry4an Brase's answer can look like

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

提交回复
热议问题