Proper way to populate model with one-to-one relationship with User model - Django
<p>I am using Djangos basic User model. There are some fields that I wanted to add to the User model for my own needs. I created a new model named <code>Profile</code> and made it have a one-to-one relationship with the User model. I can now create a user and then populate the <code>Profile</code> model that is associated with that user. However, the current implementation of populating the <code>Profile</code> model seems sloppy. For a couple reasons.</p>

<ol>
<li>I first create a user and then populate the <code>Profile</code> table. If the user didn't supply certain data then the <code>Profile</code> model wont be updated. How can I make sure the user wont be created before the <code>Profile</code>?</li>
<li><p>I want to know if there is a way to make a constructor for the <code>Profile</code> model. The current way I am populating the <code>Profile</code> model is very sloppy, here is my implementation:</p>

<pre><code>class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(write_only=True)

    def create(self, validated_data):

        user = User.objects.create_user(
            username=validated_data['email'],
            email=validated_data['email'],
        )
        user.set_password(validated_data['password'])
        user.profile.account_email = validated_data['email']
        user.profile.middle_name = validated_data['middle_name']
        user.profile.initial_name = validated_data['initial_name']
        user.profile.bio = validated_data['bio']
        user.profile.additional = validated_data['additional']
        user.save()

        return user

    class Meta:
        model = User
</code></pre></li>
</ol>

<p>Also any suggestions on the best way to approach having an extra model to keep track of extra user information would be appreciated. </p>

<p>You could make it a bit more concise</p>

<pre><code>def create(self, validated_data):

    user = User.objects.create_user(
        username=validated_data['email'],
        email=validated_data['email'],
    )
    user.set_password(validated_data.pop('password'))
    profile = UserProfile(user=user, **validated_data)
    profile.save()
    user.save()

    return user
</code></pre>

python django