Search code examples
pythondjangoone-to-onerelationships

What is the efficient way to connect models with a one to one relation?


Consider this two models,

class Engine(models.Model):
    name = models.CharField(max_length=25)


class Car(models.Model):
    name = models.CharField(max_length=25)

The two models can be connected with a OneToOneField as follows

class Engine(models.Model):
    name = models.CharField(max_length=25)
    car = models.OneToOneField(Car)

or

class Car(models.Model):
    name = models.CharField(max_length=25)
    engine = models.OneToOneField(Engine) 

Will there be any difference or what would be the difference, if the relationship is established on one model over the another.


Solution

  • There is no difference at all from an efficiency point of view; getting from one to the other will always require an extra db lookup (or a join if you do it with select_related).

    The main consideration here is probably semantic. To me, it makes more sense to say a car has an engine, so the field would go on the Car model.