如何在 Django 的 DetailView 中使用 prefetch_related

How to use prefetch_related with Django's DetailView

我想将 prefetch_relatedDjango's DetailView 一起使用。

型号:

class Customer(models.Model):
    name = models.CharField(
        verbose_name='customer name',
        max_length=100
    )
    # Other fields

class Packet(models.Model):
    customer = models.ForeignKey(
        Customer
    )
    # Other fields

class Credit(models.Model)   :
    customer = models.ForeignKey(
        Customer
    )
    # Other fields

查看:

class CustomerDetailsView(LoginRequiredMixin, DetailView):
    model = Customer
    http_method_names = ['get']
    template_name = 'detail_templates/customer_details.html'

模板:

{% for p in object.packet_set %}
    {{ do something }}
{% endif %}

{% for p in object.credit_set %}
    {{ do something }}
{% endif %}

尝试过:

class CustomerDetailsView(LoginRequiredMixin, DetailView):
    model = Customer
    http_method_names = ['get']
    template_name = 'detail_templates/customer_details.html'

    def get_queryset(self):
        queryset = super(CustomerDetailsView, self).get_queryset()
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        return queryset.filter(id=pk).prefetch_related('packet_set', 'credit_set')

debug_toolbar shows no improvement。 我如何prefetch_related packet and credit

DetailView 中使用 prefetch_related() 没有任何意义。此视图使用 get() 加载单个主对象,而 prefetch_related() 可用于加载多个主对象的相关对象。