Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize into multiple models using DjangoRestFramework

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

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

when I define a serializer for creating a new user, how do I get it to serialize data into both the user model, and the userProfile model?

like image 775
user1876508 Avatar asked May 07 '13 21:05

user1876508


1 Answers

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

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 could then use UserProfileSerializer to update (or perform other actions to) a user profile and its user instance.

like image 62
orokusaki Avatar answered Oct 12 '22 12:10

orokusaki