yernazarov
yernazarov

Reputation: 71

How to update two models through one view?

I have two models: User and Profile. Is it possible to update these two models using one PUT request? Profile looks like this:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile',
                            blank=False, null=False)
based_location = models.CharField(max_length=50, blank=True)
is_available = models.BooleanField(default=False, blank=True)

And User is AbstractUser.

I want to update with such request:

{"first_name": "John",
 "last_name": "Smith",
 "based_location": "London",
 "is_available": True,
}

Upvotes: 0

Views: 440

Answers (2)

Aprimus
Aprimus

Reputation: 1551

Override the serializer update method, pop the profile data and save the user as usual.

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['first_name', 'last_name']

    def update(self, instance, validated_data):
        based_location = validated_data.pop('based_location', None)
        is_available = validated_data.pop('based_location', None)
        if based_location and is_available:
            instance.profile.based_location = based_location
            instance.profile.is_available = is_available
            instance.profile.save(update_fields=['based_location', 'is_available'])
        return super().update(instance, validated_data)

Upvotes: 1

Roksolanka Fedkovych
Roksolanka Fedkovych

Reputation: 115

Yes, of course.

But you have to reload method put in you view and add custom logic for saving, or you can just update method perform_update.

By default it looks like:

def perform_update(self, serializer):
    serializer.save()

You can custom logic for saving both serializers

Upvotes: 1

Related Questions