[英]How can i get all related object's manytomany related field's records in Django by single query
class Author(models.Model):
name = models.CharField(max_length=50)
class Chapter(models.Model):
book = models.ForeignKey(Album, on_delete=models.CASCADE)
author = models.ManyToManyField("Author")
class Book(models.Model):
author = models.ManyToManyField("Author")
I can get Author.objects.get(id=1).chapter_set.all() and append each chapters author to the List
but how can i achieve this by query in Django我可以将 Author.objects.get(id=1).chapter_set.all() 和 append 每个章节作者添加到List
中,但是我如何通过在 Django 中的查询来实现这一点
you can follow this.你可以按照这个。
for fetching data in python you can use like this way.要在 python 中获取数据,您可以像这样使用。
fetch = Chapter.objects.all()
#and then for fetch the author
for chapter in fetch:
author_fetch = chapter.author.all()
#and now you can access the all data from author
print(author_fetch[0].name)
and for showing data to html you don't need to call author_fetch.为了向 html 显示数据,您不需要调用 author_fetch。 you can directly call it in html.您可以直接在 html 中调用它。 Here is an example这是一个例子
{% for chapter in object_list %}
{% for author in chapter.author.all %}
{{author.name}}
{% endfor %}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.