Django REST Framework,在序列化程序深度= 1时限制foreignkey关系的字段

时间:2018-03-04 17:04:50

标签: django django-rest-framework

我正在使用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']

1 个答案:

答案 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)