Difference between ForeignKey(User, unique=True) and OneToOneField [duplicate]

A OneToOneField is very similar to a ForeignKey with unique=True. Unless you are doing multiple table inheritance, in which case you have to use OneToOneField, the only real difference is the api for accessing related objects.

In the Django docs it says:

Conceptually, this is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object.

Let’s show what that means with an example. Consider two models, Person and Address. We’ll assume each person has a unique address.

class Person(models.Model):
    name = models.CharField(max_length=50)
    address = models.ForeignKey('Address', unique=True)

class Address(models.Model):
    street = models.CharField(max_length=50)

If you start with a person, you can access the address easily:

address = person.address

However if you start with an address, you have to go via the person_set manager to get the person.

person = address.person_set.get() # may raise Person.DoesNotExist

Now let’s replace the ForeignKey with a OneToOneField.

class Person(models.Model):
    name = models.CharField(max_length=50)
    address = models.OneToOneField('Address')

class Address(models.Model):
    street = models.CharField(max_length=50)

If you start with a person, you can access the address in the same way:

address = person.address

And now, we can access the person from the address more easily.

person = address.person # may raise Person.DoesNotExist

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)