Django查询与自身连接的聚合

时间:2017-01-25 09:51:28

标签: django django-queryset django-aggregation django-annotate

使用以下模型,我想选择具有验证状态的帖子最多的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'))

0 个答案:

没有答案