【问题标题】:Python Django, prefetch_related select_related for ForeignKeyPython Django,foreignKey 的 prefetch_related select_related
【发布时间】:2023-01-06 23:15:49
【问题描述】:

有两种型号:

class Batch(models.Model):
    name = models.CharField(max_length=150)

class Stage(models.Model):
    batch = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="stages")
    feild_1 = models.SmallInteterField(default=0)

看法:

class BatchWiew(ListWiew):
    model = Batch
    template_name = index.html

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['batches'] = Batch.objects.??????????????????

索引.html

{% for batch in batches %}
    {{ batch.stages.last }}
{% endfor %}

块中的“最后”

{{ batch.stages.last }}

为每个“批次”创建对数据库的附加查询。如何立即从数据库中取出必要的数据到

context['batches'] = Batch.objects.??????????????????

使用 prefetch_related、select_related 尝试了不同的选项

它不起作用

【问题讨论】:

    标签: django


    【解决方案1】:
    class BatchView(ListView):
        model = Batch
        template_name = 'index.html'
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data()
            context['batches'] = Batch.objects.prefetch_related('stages')
            return context
    

    然后,在您的模板中,您可以像这样访问每个批次的最后阶段

    {% for batch in batches %}
        {{ batch.stages.last }}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      相关资源
      最近更新 更多