With prefetch_related, I retrieve the list of my different warehouses stock like this :
Model Product
[nothing special]
Model Warehouse
[nothing special]
Model SstStock
class SstStock(models.Model):
warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
product = models.ManyToManyField(Produit)
qty = models.IntegerField()
last_update = models.DateTimeField(default=timezone.now)
views.py
class ProductListView(LoginRequiredMixin, ListView):
queryset = Product.objects.prefetch_related('sststock_set').all()
context_object_name = "produits"
paginate_by = 10
template_name = 'products/produits.html'
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(
*args, **kwargs)
context['title'] = 'Produits'
return context
Template
{% for produit in produits %}
{{ produit.sku}}<br>
{% for sst in produit.sststock_set.all %}
<span>{{ sst.warehouse.code }} - {{sst.qty}} - {{sst.qty}}</span>
{% endfor %}
{% endfor %}
But when I get the information related to the warehouse eg. sst.warehouse.code in template, the number of queries explodes. (already 36 queries with a pagination of only 10 products)
Is there a way to add warehouse in prefetch_related in the view ?