我正在使用Django REST Framework,我有一个序列化程序如下:
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
depth = 1
fields = ['user','team','correct','wrong','percentage']
如果这传递了所有user
数据(包括哈希密码),则会出现问题。如何限制传递的字段?
我有一个UserSerializer如下(它包含我真正想要的唯一字段):
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['first_name','last_name','username']
答案 0 :(得分:2)
而不是depth
选项在user
中明确声明UserProfileSerializer
字段,并在此字段中使用UserSerializer
:
class UserProfileSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = UserProfile
fields = ['user','team','correct','wrong','percentage']
或尝试覆盖build_nested_field
,如下所示:
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
depth = 1
fields = ['user','team','correct','wrong','percentage']
def build_nested_field(self, field_name, relation_info, nested_depth):
if field_name == 'user':
field_class = UserSerializer
field_kwargs = get_nested_relation_kwargs(relation_info)
return field_class, field_kwargs
return super().build_nested_field(field_name, relation_info, nested_depth)