S
S
Serj B2018-06-07 01:23:44
Django
Serj B, 2018-06-07 01:23:44

Django orm - saving to related tables?

There are 3 tables with a relationship, the default User model and:

class Place(models.Model):
    place = models.CharField()
    status = models.CharField()

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    place = models.ForeignKey(Place, on_delete=models.CASCADE)
    detail = models.CharField()

When registering a user, you need to post and save the data according to the corresponding tables. Actually the question is how to do this immediately after receiving the connection?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2018-06-07
@Serj-B

In 2018, in Django, spreading user data across two separate tables User and Profile is categorically wrong! Django has been at least 4 years old allowing you to create your own User model with all the necessary fields. Such code will be much easier to write and maintain, and the wagon and small cart of JOINs needed to load the Profile will also disappear.
But in essence the question: before saving the model instance in the database, you cannot create related models, since Django needs to know the User primary key to create them, and it is generated during the model saving process.
There is a package that allows you to get around this limitation: django-modelcluster , but in your case it is more appropriate to rewrite the user model.

M
marataziat, 2018-06-07
@marataziat

AbstractBaseUser.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question