Home > Enterprise >  Update foreign key object's fields in drf
Update foreign key object's fields in drf

Time:09-08

I've two models:

class User(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailFeild()
    password = models.CharField(max_length=255)

class Profile(models.Model):
    user = models.ForeignKeyField(User, on_delete=models.CASCADE)
    image = models.ForeignKeyField(to='media.images', on_delete=models.CASCADE)
    mobile = models.IntegerField()
    address = models.CharField(max_length=255)

Now I'm creating a patch API for updating profile. Now, a user can also update email and his name.

class ProfileUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'

    def update(self, instance, validated_data):
        .........

How would I accept the User model's detail (email and name) in the profile payload and update both the models in my serializer?

CodePudding user response:

At it simplest form, you can add two custom fields in the serializer:

class ProfileUpdateSerializer(serializers.ModelSerializer):
    name = serializers.CharField()
    email = serializers.EmailField()

And rewrite the serializer like this:

def update(self, instance, validated_data):
    name = validated_data.pop('name', '')
    email = validated_data.pop('email', '')
    instance = super().update(instance, validated_data)
    instance.user.email = email
    instance.user.name = name
    instance.user.save()
    return instance
  • Related