M
M
maksam072021-01-25 19:05:14
Django
maksam07, 2021-01-25 19:05:14

What's the best method to add new rows in related tables via OneToOneField?

Good evening. Suppose I want to extend the user model (it will be easier to explain this way) with the OneToOneField option. I will
take the code from Habr :

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

If we create a user, for example, in the admin panel and access user.profile.bio, then there will be an error that there is no row in the database and there is no such data either. On Habré, they talk about signals in django, which, when a user is added / updated, create / update a row in the Profile table. The option is not bad, but what happens if several thousand users have already been added before the creation of the Profile model? Again, they won't have those rows in the Profile table, and rows will only be created for new users.
Question. What is the best way to use model extension through OneToOneField so as not to run into exceptions when there are no related rows in the database? Or maybe it's better somehow by default to add rows to the database with default values?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-01-25
@maksam07

what happens if several thousand users have already been added before the creation of the Profile model

Well, if there is a migration that adds profiles.
What is the best way to use model extension through OneToOneField so as not to run into exceptions when there are no related rows in the database?

Add exception handling.

V
Vladimir, 2021-01-26
@AstraVlad

It all depends on the developer. You can add default values, you can add try-catch blocks, you can add logic to check for the existence of a profile when a user logs in and offer (or even require) to fill it out if not. The specific choice depends on the situation and on what you like best.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question