Mysql Django Manytomy质疑奇怪的行为

Mysql Django Manytomy质疑奇怪的行为,mysql,django,Mysql,Django,我有以下几种型号: class Post(Model): word = TextField() subscribers = ManyToManyField(User, related_name='subscribed', through='Subscription') class Subscription(Model): post = ForeignKey(Post) subscriber = ForeignKey(User) date_subsc

我有以下几种型号:

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'))
我要做的是选择所有帖子,按订阅者数量排序,如果订阅者数量相等,则按上次订阅的日期排序

我的输入数据:

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)
此查询按预期工作,但不按订阅日期排序:

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\u count
为1?还有,如何在最后一次订阅日期前正确订购

UPD:
还有一个问题。为什么
Post.objects.annotate(s_count=count('subscribers'))。按顺序‌​(“-s_count”、“-subscription_date_subscripted”).count()
给出的是4,而不是订阅中的行数?

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

您需要使用所有
订阅者的最新
订阅日期
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\u list('s\u count','subscription\u date\u subscripted'))获得的计数
,因为此时已在结果集中获取日期的各个值。

非常简单。谢谢。很高兴能帮上忙。还有一个问题。为什么Post.objects.annotate(s_count=count('subscribers')).order_by('-s_count','-subscription\u date\u subscribed')。count()给出的是4而不是订阅中的行数?预期的输出是什么?我想是订阅模型中的行数,还是它计算了Post模型中的行数?