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):
username = serializers.SerializerMethodField()
def get_username (self, obj): //obj是对应的一个对象
if obj.user:
return obj.user.username
return None
class Meta:
model = xxx
fields = ('item_id', 'xxxx','user')
depth = 1