You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中获取最新3条Recipe数据并在首页展示

解决方案

1. 添加/修改首页视图

在views.py中新增首页视图(如果已有首页视图则直接修改),获取当前用户最新的3条菜谱:

@login_required
def home(request):
    # 按添加时间倒序排序,截取前3条数据
    latest_recipes = Recipe.objects.filter(owner=request.user).order_by("-date_added")[:3]
    context = {"latest_recipes": latest_recipes}
    return render(request, "recipe_book/home.xhtml", context)

2. 配置首页URL映射

在urls.py中添加首页的URL规则:

app_name = "recipe_book"
urlpatterns = [
    # 首页路由
    path("", views.home, name="home"),
    # 现有菜谱列表页路由
    path("recipes/", views.recipes, name="recipes"),
    # 现有菜谱详情页路由
    path("recipes/<int:recipe_id>/", views.recipe, name="recipe"),
]

3. 在首页模板生成跳转按钮

在home.xhtml模板中,遍历最新菜谱数据,生成指向详情页的按钮:

{% if latest_recipes %}
    <h3>最近添加的菜谱</h3>
    {% for recipe in latest_recipes %}
        <a href="{% url 'recipe_book:recipe' recipe.id %}" style="display: inline-block; padding: 8px 16px; margin: 4px; background: #f0f0f0; border-radius: 4px; text-decoration: none;">
            {{ recipe.text }}
        </a>
    {% endfor %}
{% else %}
    <p>还没有添加任何菜谱,快去创建你的第一份菜谱吧!</p>
{% endif %}

关键说明

  • 借助order_by("-date_added")实现按添加时间从新到旧排序,[:3]在QuerySet层面直接截取前3条数据,无需加载全部菜谱,性能更高效。
  • 复用已有的recipe详情视图和URL模式,只需通过模板标签{% url 'recipe_book:recipe' recipe.id %}生成正确的跳转链接,无需额外新建详情相关逻辑。
  • 模板中加入空状态判断,避免用户未添加菜谱时出现空白区域。

内容的提问来源于stack exchange,提问作者Ylli K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:27:39