You need to enable JavaScript to run this app. Django开发食谱网站时如何按步骤分组渲染食材列表
优惠活动
大模型
产品
解决方案
定价
更多

Django开发食谱网站时如何按步骤分组渲染食材列表

实现按步骤分组展示食材的调整方案

现有实现的核心问题是get_text方法仅对全量食材做了线性排序,没有按stepnum做组级聚合,导致模板无法拆分出带步骤标题的独立展示区块。调整分两部分完成:

1. 重写模型中的get_text分组逻辑

不再返回单层的食材列表,而是按stepnum顺序聚合为带步骤标签的分组结构,同时用ORM原生排序替代Python内存排序,提升查询效率:

def get_text(self):
    # 直接通过ORM按stepnum排序查询关联食材
    ordered_ingredients = self.RecipeIngredients.all().order_by('stepnum')
    step_groups = []
    current_group = None

    for ingredient in ordered_ingredients:
        # 构造单条食材的展示元组,结构和原模板取值逻辑保持兼容
        item = (ingredient.ingredientname, ingredient.amount, ingredient.unit)
        # 遇到新的步骤分组(stepnum或step值变化)时创建新组
        if (current_group is None
            or current_group['step_label'] != ingredient.step
            or current_group['step_num'] != ingredient.stepnum):
            current_group = {
                'step_label': ingredient.step,
                'step_num': ingredient.stepnum,
                'items': []
            }
            step_groups.append(current_group)
        # 将当前食材加入对应分组
        current_group['items'].append(item)

    return step_groups

顺带修复一个模型定义的小问题:stepnum = models.IntegerField(default="0") 中默认值传了字符串类型,应该调整为 default=0,避免触发字段类型校验警告。

2. 调整模板渲染规则

基于返回的分组结构,在遍历中先渲染每个步骤的区块标题,再渲染组内的食材列表,保持原有的食材条目展示逻辑不变:

<div><h1> INGREDIENTS:  </h1></div>
<div>
    {% for step_group in recipe.get_text %}
        <h3>{{ step_group.step_label|safe }}</h3>
        <ul>
            {% for item in step_group.items %}
            <li><em>
                {{item.1|safe}} {% if item.2 is not None %} {{item.2|safe}} {% endif %} {{ item.0|safe}}
            </em></li>
            {% endfor %}
        </ul>
    {% endfor %}
</div>

调整完成后,即可实现目标展示效果:所有stepnum为0、step值为"icing"的食材,会在标题为"icing"的区块下呈现;stepnum为1、step值为"cake"的食材,会在后续标题为"cake"的区块下呈现。


内容的提问来源于stack exchange,提问作者Mickey Hoyle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.21 05:27:06