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

查看:116
本文介绍了如何按照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.

推荐答案

我刚刚找到了一种方法这样做,而不必为关系创建一个类。它依赖于额外的功能,可以为输出添加其他列。在您的示例中,它将如下所示:

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

请注意, appname_user_user_following 是Django在封面下创建的关系表的名称。这是确定性的,你可以通过元机制来获得和设置的东西,但是硬编码是非常安全的。

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.

下面是一个在封面下创建的SQL的例子,假表和列名称:

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

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

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