rest framework 序列化之depth遇到用户表外键的尴尬情况

问题:ModelSerializer序列化使用depth=1直接扩表把用户表所有信息查询出来的情况

class xxxSerializers(serializers.ModelSerializer):
    class Meta:
        model = xxx
        fields = ('item_id', 'xxxx','user')
        depth = 1

解决方式:

class xxxSerializers(serializers.ModelSerializer):
	user = serializers.SerializerMethodField()
    def get_user(self, obj):
        if obj.user:
            return obj.user.username
        return None
    class Meta:
        model = xxx
        fields = ('item_id', 'xxxx','user')
        depth = 1


你可能感兴趣的:(rest framework 序列化之depth遇到用户表外键的尴尬情况)