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

Django开发API时如何处理双重外键,在机场自动完成中展示所属国家

完全不需要修改现有数据库架构,你已经通过外键关联好了三层层级关系,直接利用Django ORM的跨表关联能力就能拿到国家信息,只需要修改序列化器、查询逻辑和前端代码即可。


步骤1:优化查询集(避免N+1性能问题)

修改视图里的查询逻辑,用select_related提前联表加载关联的城市、国家数据,避免后续序列化时反复查询数据库,提升接口性能:

class AirportList(generics.ListAPIView):
    serializer_class = AirportSerializer

    def get_queryset(self):
        airport = self.kwargs['airport']
        # 联表查询一次性取出关联的城市、国家数据
        list_airports = Airport.objects.filter(name__icontains=airport).select_related('city__country')
        return list_airports

步骤2:修改序列化器,新增国家字段

直接通过source参数指定跨关联关系取国家名称,不需要修改模型层代码:

class AirportSerializer(serializers.ModelSerializer):
    city = serializers.StringRelatedField()
    # 新增国家字段,从关联的城市的country属性取值
    country = serializers.StringRelatedField(source='city.country')

    class Meta:
        model = Airport
        # 字段列表新增abbr、country,按需展示机场代码和国家
        fields = ['name', 'abbr', 'city', 'country']

注:你之前在Airport模型里写的country = city.country是无效语法,模型类定义阶段不能直接取实例的关联属性,不需要保留这段代码。

步骤3:修改前端拼接逻辑,展示国家信息

调整接口返回数据的拼接规则,把国家信息加入自动完成的显示文本中:

new Autocomplete ('#autocomplete', {
    search: input=>{
        console.log(input)
        const url = `/airports/${input}/`
        return new Promise(resolve =>{
        fetch(url)
        .then(response => response.json())
        .then(data =>{
            // 拼接格式可按需调整:机场名称(代码), 城市, 国家
            const mappedPosts = data.map((airport)=>{return `${airport.name}(${airport.abbr}), ${airport.city}, ${airport.country}` ;})
            console.log(mappedPosts)
            resolve(mappedPosts)
        })}
        )
    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:45:03