Update Related Field

2019-09-06 19:10发布

问题:

I've been pulling my hair out trying to figure out how to do the below with django rest framework. I've got userprofile model that has a foreignkey tying back to the user table:

class UserProfile(models.Model):
    role = models.CharField(max_length=255, verbose_name='Role', choices=(('Administrator', 'Administrator'), ('User', 'User'), ('Warehouse Staff', 'Warehouse Staff')))
    adwebsite = models.ManyToManyField('ads.AdWebsite', null=True, blank=True)
    user = models.OneToOneField(User, editable=False, related_name='profile')

I'm using the following serializers:

class UserProfileSerializer(serializers.ModelSerializer):
    adwebsite = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = UserProfile
        fields = ('role', 'mobile', 'phone', 'adwebsite', 'terms_and_conditions')


class UserSerializer(serializers.HyperlinkedModelSerializer):
    groups = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups', 'first_name', 'last_name', 'is_active', 'is_staff', 'profile')
        depth = 1

If I do a GET request, it's no problem I get all of the information from the profile relation. If I do a PUT, it updates the User model, but not the UserProfile model. My payload going to the server is correct, and no errors are reported, but it doesn't save the userprofile information.

Is there something I'm doing wrong?