I am trying to expand the framework of Django rest (version 3.xx) with the fields gender , created_at , updated_at , which are defined in a separate model called UserProfile . When I try to update an instance of the UserProfile model, including a nested instance of the User model, it only updates the instance of UserProfile ( gender, updated_at fields ). So basically I want to update also the email, first_name and last_name fields from the User model
models.py:
class UserProfile(models.Model): user = models.OneToOneField(User, primary_key = True, related_name = 'profile') gender = models.CharField(choices = GENDERS, default = 2, max_length = 64) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __unicode__(self): return self.user.username @receiver(post_save, sender = User) def create_profile_for_user(sender, instance = None, created = False, **kwargs): if created: UserProfile.objects.get_or_create(user = instance) @receiver(pre_delete, sender = User) def delete_profile_for_user(sender, instance = None, **kwargs): if instance: user_profile = UserProfile.objects.get(user = instance) user_profile.delete()
serializers.py:
class UserProfileSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source = 'pk', read_only = True) username = serializers.CharField(source = 'user.username', read_only = True) email = serializers.CharField(source = 'user.email') first_name = serializers.CharField(source = 'user.first_name') last_name = serializers.CharField(source = 'user.last_name') class Meta: model = UserProfile fields = ( 'id', 'username', 'email', 'first_name', 'last_name', 'created_at', 'updated_at', 'gender', ) read_only_fields = ('created_at', 'updated_at',) def update(self, instance, validated_data):
views.py:
class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer