【问题标题】:get_absolute_url very busy databaseget_absolute_url 非常繁忙的数据库
【发布时间】:2022-08-19 08:25:20
【问题描述】:

当我加载产品页面时,我希望在该页面上提供其他产品。但是在为每个产品生成绝对 url 时,会访问数据库。因此,如果页面上有 10 个产品,那么将有 + 10 次对数据库的调用 如何减少数据库中的查询数量? 这是我的代码:

模型.py

class Goods(models.Model):
    category = models.ForeignKey(Category,
                                 related_name=\'goods\',
                                 on_delete=models.SET_NULL,
                                 null=True)

    name = models.CharField(max_length=150, db_index=True, verbose_name=\'название\')
    slug = models.CharField(max_length=150, db_index=True, unique=True, verbose_name=\'Слаг\')

    def get_absolute_url(self):
    return reverse(\'goods_detail\', kwargs={\"category_slug[enter image description here][1]\": self.category.slug, \"goods_slug\": self.slug})

网址.py

path(\'<slug:category_slug>/<slug:goods_slug>\', views.GoodsDetailView.as_view(), name=\'goods_detail\'),

视图.py

class GoodsDetailView(DetailView):
    model = Goods
    context_object_name = \'goods\'
    slug_url_kwarg = \'goods_slug\'

商品详情.html

{% for i in  goods.ingredients.all%}<br>
    <a href=\"{{ i.get_absolute_url }}\"> {{ i }}</a>
{% endfor %}

*如果我在一个页面上显示 4 个对象,照片显示了一个示例

    标签: python sql django django-debug-toolbar


    【解决方案1】:

    假设成分与货物有外键关系

    在您的 views.py 类中,您可以通过获取其他上下文来预加载信息(请参阅docs)。

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        # Add in a QuerySet of all the ingredients related to this object
        context['ingredients'] = Ingredient.objects.filter(goods = self.get_object())
        return context
    

    然后您可以在模板中引用新的上下文元素

    {% for i in ingredients %}<br>
        <a href="{{ i.get_absolute_url }}"> {{ i }}</a>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-19
      • 2013-12-26
      • 1970-01-01
      • 2012-01-29
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      相关资源
      最近更新 更多