gpt4 book ai didi

django - Django 基于类的 ListView 中的多对多 select_related

转载 作者:行者123 更新时间:2023-12-05 09:22:40 25 4
gpt4 key购买 nike

我们有一个示例模型:

#models.py
class Author(models.Model):
name = models.CharField(max_length=255)

class Book(models.Model):
name = models.CharField(max_length=255)
author = models.ManyToManyField(Author, blank=True)

def get_authors(self):
return self.authors.all().order_by('id').values_list('name')

#views.py
class BooksView(ListView):
model = Book

def get_queryset(self):
q = Book.select_related('authors').all()


#template
{% for book in books %}

{{ book.name }} ({%for author in book.get_authors %} {{ author }} {% endfor %}

{% endfor %}

当我尝试使用 get_authors 函数从模板获取数据时,我看到多个 SQL 查询显着降低了性能(SQL 工作大约 5 秒)。是否可以减少查询?现在我看到循环中每个作者的 SQL 查询。

最佳答案

M2M 使用 prefetch_related 而不是 select_related。修复模型(有不同的方法来做你想做的事):

您的模型:

class Book(models.Model):
name = models.CharField(max_length=255)
author = models.ManyToManyField(Author, blank=True)

def get_authors(self):
if self.authors:
return '%s' % " / ".join([author.name for author in self.authors.all()])

修正你的看法:

class BooksView(ListView):
"""
Note that default Django views use object_list for the context,
in order to use books, you need to define context_object_name.
"""
context_object_name = "books"
"""
You don't need to override the queryset for this kind of operation.
Just define the queryset attribute of the CBV.
"""
queryset = Book.objects.prefetch_related('authors')

然后在你的模板中:

#template
{% for book in books %}

{{ book.name }} {{ book.get_authors }}

{% endfor %}

关于django - Django 基于类的 ListView 中的多对多 select_related,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25246120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com