Junior — Middle
What does the term ForeignKey mean in the context of databases and how is it used to link tables?
sobes.tech AI
Answer from AI
In databases, the term ForeignKey refers to a field or a set of fields in one table that references the primary key of another table. This mechanism establishes and enforces a relationship between tables, helping to maintain data integrity.
For example, if there is an Orders table with a CustomerID field that is a foreign key referencing the ID field in the Customers table, then each record in Orders is linked to a specific customer in Customers.
Using a ForeignKey allows:
- Ensuring referential integrity (you cannot add an order with a non-existent customer).
- Simplifying data joins from related tables.
In Python, for example with Django ORM, a foreign key is defined as follows:
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
order_date = models.DateField()
Here, customer is a foreign key linking the order to the customer.