Foreign Key
Let's learn how to use foreign keys to control invalid semantics.
We'll cover the following
Foreign-key relationship
One approach to solving the invalid semantic issue requires a common relationship called a foreign-key relationship. Creating a foreign key involves adding the ForeignKey
argument to the Column
creation. It requires that the field labeled as a foreign key in one table corresponds to the primary key in the other table. Setting nullable
to False means that the BirthYear
record must already exist. Without the foreign key, the database would allow the book record to have no corresponding birth_year
reference. Whether to make it nullable or not depends on whether the linked-to record will already exist when the linked-from record is created.
In the following code, we’ve added a ForeignKey
to Book
:
Get hands-on with 1200+ tech skills courses.