django - 使用 prefetch_lated(model_SET).all() 获取相关模型外键(除了 ManyToMany 之外)

标签 django django-templates prefetch

通过 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 a auto_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 in ModelForms by default.

关于django - 使用 prefetch_lated(model_SET).all() 获取相关模型外键(除了 ManyToMany 之外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71413522/

相关文章:

html - Safari 浏览器的预取解决方案?

android - RecyclerView 中的预取文本布局,无法解析方法 setTextFuture

django - 大家好,我正在编写你的第一个 Django 应用程序,第 2 部分教程,我尝试了 _str_() 函数,但它没有给我相同的结果

python - 为什么这个 django 表单无效?

python - 我需要有关如何在 Django 中实现复选框的建议

Django:嵌套属性上的 Prefetch_lated

python - 使用工作台连接到 Django 中的 MySQL 数据库

django - 编写 Django 脚本

Django:AttributeError 'WSGIRequest' 对象没有属性 'get'

python - Django 模板迭代嵌套列表