Django OneToOneField - Add to parent or Child?

Viewed 68

What is the proper way to add a OneToOneField in Django? Does it go in the parent class or child class? The official docs don't really explain this. Which way works better with the built-in admin interface? Does it matter? Is there a convention?

What is the "correct" way?

class Client(models.Model):
    name = models.CharField(max_length=30)
    portfolio = models.OneToOneField(to="Portfolio", null=True, on_delete=models.CASCADE)

class Portfolio(models.Model):
    ... portfolio fields ...

or

class Client(models.Model):
    name = models.CharField(max_length=30)

class Portfolio(models.Model):
    client = models.OneToOneField(to="Client", null=True, on_delete=models.CASCADE)
    ... portfolio fields ...

I see most examples add it to the child, but it seems adding it to the parent works better with the admin interfaces and makes more sense logically.

1 Answers

It's generally better to add in child class, but these things are done according to form's presentation, since adding the portfolio while adding the client in Client model is more logical than adding the client in the Portfolio model, same goes for ManyToManyField, as documentation says in one of it's example of Pizza and Topping model, that it's more logical to add how many kinds of toppings in a pizza than adding how many pizzas will be made through particular topping.

So, I'd recommend you to go with first approach.

Does it matters?

It's not necessarily matters while querying too, if you query through select_related, performance is not affected.

Related