如何按 Django 中 ManyToManyField 的 id 排序? [英] How can I sort by the id of a ManyToManyField in Django?

查看:24
本文介绍了如何按 Django 中 ManyToManyField 的 id 排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用户对象中有一个 ManyToManyField,它用于映射用户关注的用户.我正在尝试显示他们最近关注的人的子集列表..order_by() 中是否有一个技巧可以让我按 ManyToManyField 的 id 进行排序?数据在那里,对吗?

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 followed. Is there a trick in .order_by() that will allow me to sort by the id of the ManyToManyField? The data is there, 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")

这会给我一个用户关注的用户列表,但按他们加入的时间排序.我希望以下列表的顺序按照用户关注它们的时间顺序排列.

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

推荐答案

事实上(至少在 Django 1.10 中),你不需要使用 extra 特性,而是可以通过 order by场直接.只需使用自动创建的通过表名后跟.id"作为 order_by 的参数.例如

In fact (at least in Django 1.10), you don't need to use the extra feature but instead can just order by the field directly. Just use the automatically created through table name followed by ".id" as an argument to order_by. E.g.

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

许多其他解决方案建议创建自定义直通表并添加字段,但如果您只想按自动生成直通表的 id 进行排序,则没有必要.

Many other solutions suggest creating a custom through table and adding a field but if you just want to sort by the id of the automatically generated through table then this is not necessary.

这篇关于如何按 Django 中 ManyToManyField 的 id 排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆