7

My understanding is that OneToOneField is used for just 1 row of data from Table2 (Favorite fruit) linked to one row of data in Table1 (Person's name), and ForeignKey is for multiple rows of data in Table2 (Car models) to 1 row of data in Table1 (Brand/Manufacturer).

My question is what should I use if I have multiple tables but only one row of data from each table that links back to Table1. For example: I have Table1 as "Cars", my other tables are "Insurance Info", "Car Info", "Repair History". Should I use ForeignKey or OneToOne?

2 Answers 2

15

You just need to ask yourself "Can object A have many object B, or object B many object A's"?

Those table relations each could be different:

  1. A Car could have 1 or many insurance policies, and an insurance policy only applies to one car. If the car can only have one, then it could be a one-to-one.
  2. A Car can have many repair history rows, so this would be a foreign key on the repair history, with a back relation to the Car as a set.
  3. Car Info is similar to the UserProfile concept in django. If it is truly unique information, then it too would be a one-to-one. But if you define Car Info as a general description that could apply to similar Car models, then it would be a foreign key on the Car Table to refer to the Car Info
2
  • Thanks for the quick answer! Very straightforward and easy to understand. :)
    – Wesley
    Commented Aug 24, 2012 at 19:35
  • Sure thing. If you need extra info let me know. Otherwise don't forget to hit the checkmark if this solves your problem
    – jdi
    Commented Aug 24, 2012 at 19:59
3

ForeignKey means that you are referencing an element that exists inside of another table. OneToOne, is a type of ForeignKey in which an element of table1 and table2 are uniquely bound together.

Your favorite fruit example would be OneToMany. Because each person has a unique favorite fruit, but each fruit can have multiple people who list that particular fruit as their favorite.

A OneToOne relationship may be done with your Car example. Cars.VIN could have a OneToOne relationship with CarInfo.VIN since one car will only ever have one CarInfo associated with it (and vise versa).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.