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)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A
OneToOneFieldis very similar to aForeignKeywithunique=True. Unless you are doing multiple table inheritance, in which case you have to useOneToOneField, the only real difference is the api for accessing related objects.In the Django docs it says:
Let’s show what that means with an example. Consider two models,
PersonandAddress. We’ll assume each person has a unique address.If you start with a person, you can access the address easily:
However if you start with an address, you have to go via the
person_setmanager to get the person.Now let’s replace the
ForeignKeywith aOneToOneField.If you start with a person, you can access the address in the same way:
And now, we can access the person from the address more easily.