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

Django项目求助:生成待处理/已通过预订的结构化API输出

修正你的Django预订数据返回逻辑

我看了你的代码,能发现几个关键问题导致无法生成符合要求的结果,咱们一步步来修正:

主要问题分析

  • 你试图用data["upcoming_pending"][a.id]给列表赋值,但列表是有序集合,不能直接用ID当索引,应该用append()添加字典元素
  • reservations.objects.filter(id=a.id)返回的是QuerySet,不是单个预订对象,其实循环里的a已经是单个预订实例了,直接用它就行
  • 变量ser没有定义,你需要从当前预订关联的服务中获取对应的ID集合
  • 第二个循环里误用了a.id,应该是b.id
  • 没有把预订的字段(比如arrival_date、location_name等)映射到需求的结构里

修正后的完整代码

假设你的模型结构大概是这样(如果和实际有出入,你可以调整字段名):

  • Reservation模型包含id、user、location(外键到Location模型)、arrival(datetime字段)、departure(datetime字段)、status、comments等字段
  • Service模型包含id、title、description、type(1=服务,2=附加项),且Reservation和Service是多对多关联(或者通过中间表关联)
from django.http import JsonResponse
from datetime import datetime
from .models import reservations, services  # 注:Django模型名建议用大驼峰,比如Reservation、Service,符合规范

def get_upcoming_reservations(request):
    user_id = request.user.id  # 假设你从请求上下文获取用户ID
    data = {
        "upcoming_pending": [],
        "upcoming_approved": []
    }

    # 处理待处理预订
    pending_reservations = reservations.objects.filter(
        user_id=user_id,
        arrival__gte=datetime.now(),
        status=0
    )
    for res in pending_reservations:
        # 构建单个预订的字典结构
        reservation_data = {
            "reservation_id": res.id,
            "location_id": res.location.id,
            "location_name": res.location.name,  # 假设Location模型有name字段
            "arrival_date": res.arrival.date().isoformat(),
            "arrival_time": res.arrival.time().isoformat(),
            "departure_date": res.departure.date().isoformat(),
            "departure_time": res.departure.time().isoformat(),
            "services": [],
            "add-ons": [],
            "comments": res.comments or ""
        }

        # 获取当前预订关联的所有服务,按type分类
        all_services = res.services.all()
        # 填充服务列表(type=1)
        reservation_data["services"] = [
            {
                "service_id": s.id,
                "service_title": s.title,
                "service_description": s.description
            }
            for s in all_services if s.type == 1
        ]
        # 填充附加项列表(type=2)
        reservation_data["add-ons"] = [
            {
                "service_id": s.id,
                "service_title": s.title,
                "service_description": s.description
            }
            for s in all_services if s.type == 2
        ]

        # 添加到待处理列表
        data["upcoming_pending"].append(reservation_data)

    # 处理已通过预订,逻辑和待处理一致
    approved_reservations = reservations.objects.filter(
        user_id=user_id,
        arrival__gte=datetime.now(),
        status=1
    )
    for res in approved_reservations:
        reservation_data = {
            "reservation_id": res.id,
            "location_id": res.location.id,
            "location_name": res.location.name,
            "arrival_date": res.arrival.date().isoformat(),
            "arrival_time": res.arrival.time().isoformat(),
            "departure_date": res.departure.date().isoformat(),
            "departure_time": res.departure.time().isoformat(),
            "services": [],
            "add-ons": [],
            "comments": res.comments or ""
        }

        all_services = res.services.all()
        reservation_data["services"] = [
            {
                "service_id": s.id,
                "service_title": s.title,
                "service_description": s.description
            }
            for s in all_services if s.type == 1
        ]
        reservation_data["add-ons"] = [
            {
                "service_id": s.id,
                "service_title": s.title,
                "service_description": s.description
            }
            for s in all_services if s.type == 2
        ]

        data["upcoming_approved"].append(reservation_data)

    return JsonResponse({"result": data}, status=200)

额外优化建议

  1. 模型命名规范:Django模型名建议用大驼峰(比如Reservation而不是reservations),符合PEP8编码规范
  2. 减少数据库查询:可以用select_related和prefetch_related优化查询,避免循环中多次访问数据库:
    pending_reservations = reservations.objects.filter(
        user_id=user_id,
        arrival__gte=datetime.now(),
        status=0
    ).select_related('location').prefetch_related('services')
    
  3. 代码复用:把构建预订数据的逻辑抽成函数,避免重复代码:
    def build_reservation_data(res):
        all_services = res.services.all()
        return {
            "reservation_id": res.id,
            "location_id": res.location.id,
            "location_name": res.location.name,
            "arrival_date": res.arrival.date().isoformat(),
            "arrival_time": res.arrival.time().isoformat(),
            "departure_date": res.departure.date().isoformat(),
            "departure_time": res.departure.time().isoformat(),
            "services": [
                {"service_id": s.id, "service_title": s.title, "service_description": s.description}
                for s in all_services if s.type == 1
            ],
            "add-ons": [
                {"service_id": s.id, "service_title": s.title, "service_description": s.description}
                for s in all_services if s.type == 2
            ],
            "comments": res.comments or ""
        }
    
    之后循环里直接调用data["upcoming_pending"].append(build_reservation_data(res))即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:58:36