gpt4 book ai didi

python - Bootstrap Accordion 与 Django : How to only load the data for the open accordion section?

转载 作者:太空宇宙 更新时间:2023-11-04 05:21:40 24 4
gpt4 key购买 nike

我正在尝试制作一个网页,它将以 Bootstrap Accordion 的格式显示食谱,就像这样 ( see here )。这就是我现在的做法:

<div class="panel-group" id="accordion">
{% for recipe in recipes %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}">
{{ recipe }}
</a>
</h4>
</div>
<div id="collapse{{ forloop.counter }}" class="panel-collapse collapse">
<div class="panel-body">
<table class="table table-hover">
{% for ingredient in foodtype|ingredients_in_recipe:recipe %}
<tr>
<td>
{{ ingredient.ingredient_name }}
</td>
<td>
{{ ingredient.ingredient_quantity }}
</td>
</tr>
{% endfor %}
<p>{{ recipe.details }}</p>
</table>
</div>
</div>
</div>
{% endfor %}
</div>

我为此做了一个自定义模板标签:

@register.filter
def ingredients_in_recipe(foodtype, recipe):
return foodtype.ingredient_set.filter(recipe=recipe).order_by("ingredient_name")

问题是我有 200 多个食谱,加载所有这些数据的速度太慢了。理想情况下,模板标签函数 ingredients_in_recipe 应该只在用户点击食谱时被调用。然而,据我所知,这是不可能的,因为 Django 运行它,然后将呈现的 HTML 发送给用户。

有没有办法绕过这个问题,同时仍然保持图片中的 Accordion 风格?

提前致谢,最大

编辑:这也是我的观点

def detail(request, foodtype_id):
foodtype = get_object_or_404(foodtype, id=foodtype_id)
recipe = foodtype.recipe_set.values_list('recipe').order_by('recipe').distinct()
context = {
'foodtype': foodtype,
'recipe': recipe,
}
return render(request, 'main/detail.html', context)

最佳答案

总是最好在到达模板之前执行该逻辑。如果您设置成分的顺序,那么您就不必在模板中订购它们会怎么样?这是否有效并提高了性能?

class Ingredient(models.Model):
...

class Meta:
ordering = ['ingredient_name']


<div class="panel-group" id="accordion">
{% for recipe in recipes %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}">
{{ recipe }}
</a>
</h4>
</div>
<div id="collapse{{ forloop.counter }}" class="panel-collapse collapse">
<div class="panel-body">
<table class="table table-hover">
{% for ingredient in recipe.ingredient_set.all %}
<tr>
<td>
{{ ingredient.ingredient_name }}
</td>
<td>
{{ ingredient.ingredient_quantity }}
</td>
</tr>
{% endfor %}
<p>{{ recipe.details }}</p>
</table>
</div>
</div>
</div>
{% endfor %}
</div>

关于python - Bootstrap Accordion 与 Django : How to only load the data for the open accordion section?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40077880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com