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

Django REST如何通过related_name获取序列化器关联表指定字段

问题根因

DRF默认序列化反向关联的外键字段时,会默认使用PrimaryKeyRelatedField,所以你直接把关联名phones放入字段列表时,只会返回关联的ContactPhone对象的id列表,不会返回其他字段。

方案1:嵌套序列化器(推荐)

先单独定义ContactPhone的序列化器,指定需要返回的字段,再在Lead序列化器中显式声明phones字段使用该序列化器,加上many=True适配一对多关系:

# 先定义ContactPhone的序列化器
class ContactPhoneSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContactPhone
        # 按需保留需要返回的字段,这里保留了id、手机号、手机号类型
        fields = ('id', 'phone_number', 'phone_type')

class LeadListSerializer(serializers.ModelSerializer):
    # 显式指定phones字段使用自定义序列化器,只读+一对多配置
    phones = ContactPhoneSerializer(many=True, read_only=True)

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

该方案扩展性强,后续需要返回ContactPhone的其他字段时,只需要调整ContactPhoneSerializer的字段列表即可。

方案2:SerializerMethodField(仅需返回手机号时使用)

如果你只需要返回手机号列表,不需要其他ContactPhone属性,可以用SerializerMethodField自定义取值逻辑:

class LeadListSerializer(serializers.ModelSerializer):
    phones = serializers.SerializerMethodField()

    def get_phones(self, obj):
        # 直接返回所有关联的手机号字符串列表
        return [phone.phone_number for phone in obj.phones.all()]

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

性能优化提示

查询Lead列表时,建议给查询集加上prefetch_related('phones')预加载关联的ContactPhone数据,避免出现N+1查询问题,提升接口响应速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:06:03