Alexxio
Alexxio

Reputation: 1101

How to save data in models with oneToOne relationship

I have this model

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    role = models.CharField(max_length=30)

If I receive the data username, firstname, lastmame, email,passsword, role, How am I going to create a profile for this user, given that 'role' is not in the User model. its in UserProfile model.

Upvotes: 0

Views: 142

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

This is very basic but it works and I'm guessing you're using the Django User model?

user = User.objects.create_user(username, email, password)
user.first_name = firstname
user.last_name = lastname
user.save()

user_profile, created = UserProfile.objects.create_or_create(user=user, role=role)

What I would recommend doing if you find yourself doing this a lot is overriding the manager objects with a custom manager method.

class UserProfileManager(models.Manager):
    def create_profile(self, user, role):
        profile = self.create(user=user, role=role)
        return profile

you could then call it with this:

profile = UserProfile.objects.create_profile(user, role)

Upvotes: 1

Related Questions