[英]django query annotate values get list from reverse foreign key
I have a simple model like我有一个简单的 model 之类的
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Here I want to queryall authors with the title of all the blogs they have written like这里我想用他们写过的所有博客的标题查询all authors like
Author One : [Blog One, Blog Two, Blog Three]
I want this from query and not loop我想要这个来自查询而不是循环
Here my approach is to use subquery like在这里我的方法是使用子查询
blogs =Blog.objects.filter(author=OuterRef('pk')).values("title")
authors = Author.objects.annotate(blogs=Subquery(blogs), output_field=CharField())
But here I am getting error like sub-select returns 2 columns - expected 1
但在这里我收到错误,例如sub-select returns 2 columns - expected 1
How can I get all the authors with all the blogs they have written?我怎样才能得到所有作者和他们写的所有博客? I do not want to use loop.我不想使用循环。 I want this through query我想通过查询
If you are using a postgres
as a database, then you can use an ArrayAgg
function:如果您使用postgres
作为数据库,则可以使用ArrayAgg
function:
from django.contrib.postgres.aggregates import ArrayAgg
authors = Author.objects.annotate(blogs=ArrayAgg('blog_set__title'))
You can query with:您可以查询:
authors = Author.objects.prefetch_related('blog_set')
Then in the template, you can render with:然后在模板中,你可以渲染:
<ul>
{% for author in authors %}
<li>{{ author }}</li>
<ul>
{% for blog in author.blog_set.all %}
<li>{{ blog }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.