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

求助:Django Rest Framework多模型自定义JSON结构返回及相关问题

解决Django Rest Framework中自定义多模型JSON响应格式的问题

首先得指出你期望的JSON格式存在语法错误——数组([])内部不能直接放置键值对(比如"postal code": {...}),这会导致JSON解析失败。我先帮你修正为合理的结构:把postal code、suburb、state嵌套在country数组的对象内部,类似这样:

{
  "message": "success",
  "code": 200,
  "country": [
    {
      "country_name": "nepal",
      "country_code": "977",
      "postal code": {"post_code": 105},
      "suburb": {"suburb_name": "damak"},
      "state": {"state_name": "india1"}
    }
  ]
}

接下来,你完全不需要重写drf_multiple_models,手动构建响应结构就足够灵活。修改你的视图代码即可实现需求:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Country, Post, Suburb, State

class InformationList(APIView):
    def get(self, request):
        # 提取查询参数
        country_code = self.request.query_params.get('country')
        post_code = self.request.query_params.get('post')
        suburb_name = self.request.query_params.get('city')
        state_name = self.request.query_params.get('state')
        
        # 获取单个匹配对象,处理无结果的情况(避免返回None)
        country_data = Country.objects.filter(country_code=country_code).values('country_name', 'country_code').first() or {}
        post_data = Post.objects.filter(post_code=post_code).values('post_code').first() or {}
        suburb_data = Suburb.objects.filter(suburb_name=suburb_name).values('suburb_name').first() or {}
        state_data = State.objects.filter(state_name=state_name).values('state_name').first() or {}
        
        # 嵌套整合数据
        if country_data:
            country_data["postal code"] = post_data
            country_data["suburb"] = suburb_data
            country_data["state"] = state_data
        
        # 返回自定义结构的响应
        return Response({
            "message": "success",
            "code": status.HTTP_200_OK,
            "country": [country_data] if country_data else []
        })

关键修改点说明:

  • 使用.first()获取单个查询结果:你的查询参数应该是匹配单条记录,这样可以避免返回数组,方便后续嵌套整合
  • 处理无结果场景:用or {}确保即使查询不到数据,也不会返回None,避免JSON序列化错误
  • 手动嵌套数据:把postal code、suburb、state的结果直接添加到country对象中,再放入数组,符合你想要的嵌套结构
  • 无需第三方库:这种场景下手动构建响应比依赖drf_multiple_models更直观,也更容易控制最终格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:47:40