What is different between models.ForeignKey(Modelname, unique=True) and models.OneToOneField in Django?
Where should I use models.OneToOneField and models.ForeignKey(Modelname, unique=True)?
The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.
This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle. One-to-one relations are defined using OneToOneField field of django.
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. courses.Courses.id: (fields. W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOne Field. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
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
ForeignKeywithunique=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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With