通过 prefetch_lated,我可以检索不同仓库库存的列表,如下所示:
模型产品
[没什么特别的]
模型仓库
[没什么特别的]
型号 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
模板
{% 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 %}
但是当我获得与仓库相关的信息时,例如。模板中的sst.warehouse.code
,查询数量爆炸式增长。 (已经有 36 个查询,分页只有 10 个产品)
有没有办法在 View 中的prefetch_lated中添加warehouse?
最佳答案
您可以使用 Prefetch
object [Django-doc] :
class ProductListView(LoginRequiredMixin, ListView):
queryset = Product.objects.prefetch_related(
Prefetch('sststock_set', SstStock.objects<strong>.select_related('warehouse')</strong>)
))
# …
Note: Django's
DateTimeField
[Django-doc] has aauto_now=…
parameter [Django-doc] to work with timestamps. This will automatically assign the current datetime when updating the object, and mark it as non-editable (editable=False
), such that it does not appear inModelForm
s by default.
关于django - 使用 prefetch_lated(model_SET).all() 获取相关模型外键(除了 ManyToMany 之外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71413522/