Sobes.tech
Junior — Middle

What is the purpose of the ForeignKey field in database models?

sobes.tech AI

Answer from AI

The ForeignKey field in database models is used to create a relationship between two tables. It indicates that the value in one field references the unique identifier (usually the primary key) of another table.

This allows implementing 'one-to-many' or 'many-to-one' relationships. For example, in an "Order" model, the ForeignKey field can reference the "User" model, showing which user placed the order.

Example in Django ORM:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)

class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.CharField(max_length=100)

Here, the user field in the Order model is a ForeignKey linking the order to a specific user.