Django DRF | Modify parent model field while creating a Child model

时间:2019-03-06 11:35:02

标签: django django-rest-framework

I have a User model and another Admin model which has a OneToOne relationship with User model.

I am trying to modify a field in User model while an Admin model is being created.

Here is my Serializer for admin model:

class AdminSerializer(serializers.ModelSerializer):
    """A Serizlier class for vendor """

    user = UserSerializer()

    class Meta:
        model = models.Admin
        fields = ('user', 'first_name', 'last_name', 'dob', 'gender')

        # This didn't work, also user_type is a field in User model and not Admin model
        read_only_fields = ('user_type',)


    def create(self, validated_data): # override this method <<<
        """
        Since the "user" is a read_only field, the validated data doesn't contain it.
        """

        # Line that causes the error. Trying to modify User model field
        validated_data['user_type'] = constants.Constants.ADMIN
        return super().create(validated_data)

but I get an error:

The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer letzbargain_api.serializers.AdminSerializer, or set read_only=True on nested serializer fields

How can I fix this?

1 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,则您希望创建Admin,但希望将Admin的{​​{1}}的{​​{1}}保持只读。

要执行此操作,必须确保user的指定用户序列化程序中的user_type是只读的。例如,我正在编写一个新的序列化器:

user_type

现在在您的AdminSerializer中使用该地址:

class AdminUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = ('foo', 'bar', 'user_type')
        read_only_fields = ('user_type',)