How to serialize to multiple models using DjangoRestFramework

I have defined a user profile model, but I want to have one api endpoint that saves all user data in both models. By this, I mean that I am using a user model, and I have a user profile model defined as follows

class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) biography = models.TextField() 

when I define a serializer to create a new user, how can I get it to serialize data in both the user model and the userProfile model?

+6
source share
1 answer

You just need to define a serializer for each and attach one to the other, as shown below:

 from rest_framework.serializers import ModelSerializer class UserSerializer(ModelSerializer): """ A serializer for ``User``. """ class Meta(object): model = User class UserProfileSerializer(ModelSerializer): """ A serializer for ``UserProfile``. """ user = UserSerializer() class Meta(object): model = UserProfile 

You can then use the UserProfileSerializer to update (or perform other actions) the user profile and its user instance.

+18
source

Source: https://habr.com/ru/post/944482/


All Articles