简体   繁体   English

如何合并两个查询集Django

[英]How to merge two querysets django

I'm trying to get a list of latest 100 posts and also the aggregated count of approved, pending, and rejected posts for the user of that post. 我正在尝试获取最新100条帖子的列表,以及该帖子用户的已批准,待处理和已拒绝帖子的总数。

models.py models.py

class BlogPost(models.Model):
    POST_STATUSES = (
                    ('A', 'Approved'),
                    ('P', 'Pending'),
                    ('R', 'Rejected')
                    )
    author = models.ForeignKey(User)
    title = models.CharField(max_length=50)
    description = models.TextField()
    status = models.ChoiceField(max_length=1, choices=POST_STATUSES)

views.py views.py

Now I'm getting the the aggregated count like so, but I'm confused on how to merge the count with the title of the posts 现在,我得到了这样的汇总计数,但是我对如何将计数与帖子标题合并感到困惑

top_post_users = list(BlogPost.objects.values_list('user_id', flat=True))[:100]
users =  User.objects.filter(pk__in=top_post_users).annotate(approved_count=Count(Case(When(user_posts__status="A", then=1),output_field=IntegerField()))).annotate(pending_count=Count(Case(When(user_posts__status="P", then=1),output_field=IntegerField()))).annotate(reject_count=Count(Case(When(user_posts__status="R", then=1),output_field=IntegerField())))
users.values('approved_count', 'pending_count', 'reject_count')

This is the result I want: 这是我想要的结果:

  • Title Of Post, Author1, 10, 5, 1 标题,作者1,10,5,1
  • Title Of Post2, Author2, 7, 3, 1 标题2,作者2、7、3、1
  • Title Of Post3, Author1, 10, 5, 1 标题3,作者1,10,5,1

How can I merge the returned counts with the titles? 如何将返回的计数与标题合并?

I know I could use a for loop and append each one, but efficiency wise I don't think this is the right way to do it. 我知道我可以使用for循环并附加每个循环,但是出于效率考虑,我认为这不是正确的方法。 Is there a more efficient way using django database ORM? 有没有使用Django数据库ORM的更有效方法?

I've tried this 我已经试过了

users.values('title', approved_count', 'pending_count', 'reject_count') users.values('标题',批准计数','待定计数','拒绝计数')

...and that works, but it returns more than the latest 100 posts, so I think it's getting all the posts for those users and the aggregated count. ...而且行得通,但返回的信息超过了最新的100条,所以我认为它正在获取这些用户的所有信息和总计。

Ultimately, you want a list of BlogPosts: 最终,您需要一个BlogPost列表:

main_qs = BlogPost.objects
# add filters, ordering etc. of the posts

and you want to display not only the authors next to the title of the post but also enrich the author information with the annotated counts. 而且您不仅要在帖子标题旁边显示作者,还要用带注释的计数丰富作者信息。

from django.db.models import OuterRef, Subquery, Count

# you need subqueries to annotate the blog posts
base_sub_qs = BlogPost.objects.filter(author__pk=OuterRef('author__pk'))

# add subqueries for each count
main_qs = main_qs.annotate(
    user_approved_count=Subquery(base_sub_qs.filter(status="A").annotate(
            c=Count('*')).values('c'), output_field=IntegerField()),
    user_pending_count=Subquery(base_sub_qs.filter(status="P").annotate(
            c=Count('*')).values('c'), output_field=IntegerField()),
    user_rejected_count=Subquery(base_sub_qs.filter(status="R").annotate(
            c=Count('*')).values('c'), output_field=IntegerField()),
)

You can then access these in your template: 然后,您可以在模板中访问它们:

{% for post in posts %}
    {{ post.title }}
    {{ post.author.get_full_name }}
    approved: {{ post.user_approved_count }}
    pending: {{ post.user_pending_count }}
    rejected: {{ post.user_rejected_count }}
{% endfor %}

Documentation: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#subquery-expressions 文档: https : //docs.djangoproject.com/en/2.1/ref/models/expressions/#subquery-expressions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM