gpt4 book ai didi

mysql - Django manytomany 查询奇怪的行为

转载 作者:行者123 更新时间:2023-11-28 23:22:05 25 4
gpt4 key购买 nike

我有以下模型:

class Post(Model):
word = TextField()
subscribers = ManyToManyField(User, related_name='subscribed', through='Subscription')

class Subscription(Model):
post = ForeignKey(Post)
subscriber = ForeignKey(User)
date_subscribed = DateTimeField(default=timezone.now)

class Meta:
ordering = ('-date_subscribed', )
unique_together = (('post', 'subscriber'))

我想做的是选择所有帖子,按订阅者数量排序,如果订阅者数量相等,则按上次 date_subscribed 排序。

我的输入数据:

post1 = Post(text="post1")
post2 = Post(text="post2")
post3 = Post(text="post3")
post4 = Post(text="post4")

user1 = User(username="user1")
user2 = User(username="user2")
user3 = User(username="user3")
user4 = User(username="user4")

Subscription.objects.create(post=post1, user=user1)
Subscription.objects.create(post=post2, user=user1)
Subscription.objects.create(post=post3, user=user1)
Subscription.objects.create(post=post3, user=user2)
Subscription.objects.create(post=post3, user=user3)
Subscription.objects.create(post=post3, user=user4)
Subscription.objects.create(post=post4, user=user1)
Subscription.objects.create(post=post4, user=user2)
Subscription.objects.create(post=post4, user=user3)

此查询按预期工作,但未按 date_subscribed 排序:

Post.objects.annotate(s_count=Count('subscribers')).order_by('-s_count')

当我写的时候:

Post.objects.annotate(s_count=Count('subscribers')).order_by('-s_count', '-subscription__date_subscribed') 

我得到了奇怪的结果,我真的不明白这种行为。对于上面的数据,它输出所有带有 s_count=1 的帖子。

为什么 s_count 是 1?还有,如何在上次 date_subscribed 之前正确订购?

更新:还有一个问题。为什么 Post.objects.annotate(s_count=Count('subscribers')).order_by‌ ('-s_count', '-subscription__date_subscribed').count() 给出 4 而不是订阅中的行数?

最佳答案

由于 SubscriptionPostSubscriber 之间 m2m 关系的直通表,当您在 Subscription 的字段上订购时 模型本身,所有帖子在结果集中显示为单独的行,这就是为什么您得到 s_count=1 的原因,因为具有特定订阅者的每个帖子都是唯一的。

您需要使用所有订阅者 的最新date_subscribed 注释Post 对象,然后在注释字段上排序:

posts = Post.objects.annotate(
s_count=Count('subscribers'),
s_date_max=Max('subscription__date_subscribed')
).order_by('-s_count', '-s_date_max')

下一个问题的更新:

如果您使用count() 方法,它将返回帖子 的数量。您可以看到它与您从 len(queryset.values_list('s_count', 'subscription__date_subscribed')) 获得的计数不同,因为此时日期的各个值已在结果中提取设置。

关于mysql - Django manytomany 查询奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41137824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com