Issue
I want to use prefetch_related
with Django's DetailView
.
Model:
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
View:
class CustomerDetailsView(LoginRequiredMixin, DetailView):
model = Customer
http_method_names = ['get']
template_name = 'detail_templates/customer_details.html'
Templates:
{% for p in object.packet_set %}
{{ do something }}
{% endif %}
{% for p in object.credit_set %}
{{ do something }}
{% endif %}
Tried:
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
.
How do I prefetch_related packet and credit
Solution
There is no sense to use prefetch_related()
in the DetailView
. This view loads the single master object with get()
while prefetch_related()
is usable for loading related objects of multiple master objects.
Answered By - catavaran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.