1

使用以下模型,我想选择在验证状态下拥有最多帖子的 root 用户(在单个查询中或至少以优化的方式)。在我的情况下,root 用户不是直接作者,我想在 root 用户上聚合子用户作者。

class User(models.Model):
    name = models.CharField(max_length=255)
    # root users have no root
    root = models.ForeignKey('User', blank=True, null=True)

class Post(models.Model):
    STATE_CHOICES = (
        (0, 'Writting'),
        (1, 'Reviewing'),
        (2, 'Validated'),
        (3, 'Published'),
        (4, 'Removed'),
    )
    state = models.IntegerField(choices=STATE_CHOICES, default=0)
    # authors are no root user
    author = models.ForeignKey('User')

# all validated but not published posts:
Post.objects.filter(state=2)

# all user having validated but not published posts:
User.objects.filter(post__state=2)

# same with number of posts
User.objects.filter(post__state=2).annotate(post_count=Count('post'))

# same ordered by number of posts
User.objects.filter(post__state=2).annotate(post_count=Count('post')).order_by('-post_count')

# same keeping only the top 10
User.objects.filter(post__state=2).annotate(post_count=Count('post')).order_by('-post_count')[:10]

# same aggregated for root users: NOT WORKING!
User.objects.filter(user__post__state=2).annotate(post_count=Count('post')).order_by('-post_count')[:10]  # FieldError: Cannot resolve keyword 'user' into field.
User.objects.filter(root__post__state=2).annotate(post_count=Count('post')).order_by('-post_count')[:10]  # no result

这个问题可能与同一模型上缺少后向关系有关?

# works:
User.objects.filter(post__author=F('id'))

# not working:
User.objects.filter(user__root=F('id'))
4

0 回答 0