Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which to use: OneToOne vs ForeignKey?

Tags:

python

django

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?

like image 697
Wesley Avatar asked Aug 24 '12 18:08

Wesley


People also ask

What is the difference between foreign key and many to many relationship?

A foreign key relationship is generally known as a many-to-one relationship. Note that the reverse of this relationship is one-to-many (which Django provides tools to access). As the name implies, many objects may be related to one.

WHAT IS models ForeignKey?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db.

What is a one-to-one field?

One-to-one fields: This is used when one record of a model A is related to exactly one record of another model B. This field can be useful as a primary key of an object if that object extends another object in some way.

What is Primary_key true?

Since a primary key means a value that can uniquely identify an object. In the documentation on the primary_key parameter, we see: Field.primary_key. If True , this field is the primary key for the model.


1 Answers

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
like image 182
jdi Avatar answered Nov 14 '22 22:11

jdi