Django Model Field Reference ForeignKey

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

ForeignKey field is used to create a many-to-one relationship between models. Not like the most of other fields requires positional arguments. The following example demonstrates the car and owner relation:

from django.db import models

class Person(models.Model):
    GENDER_FEMALE = 'F'
    GENDER_MALE = 'M'

    GENDER_CHOICES = (
        (GENDER_FEMALE, 'Female'),
        (GENDER_MALE, 'Male'),
    )

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    age = models.SmallIntegerField()


class Car(model.Model)
    owner = models.ForeignKey('Person')
    plate = models.CharField(max_length=15)
    brand = models.CharField(max_length=50)
    model = models.CharField(max_length=50)
    color = models.CharField(max_length=50)

The first argument of the field is the class to which the model is related. The second positional argument is on_delete argument. In the current versions this argument is not required, but it will be required in Django 2.0. The default functionality of the argument is shown as following:

class Car(model.Model)
    owner = models.ForeignKey('Person', on_delete=models.CASCADE)
    ...

This will cause Car objects to be deleted from the model when its owner deleted from Person model. This is the default functionality.

class Car(model.Model)
    owner = models.ForeignKey('Person', on_delete=models.PROTECT)
    ...

This will prevents Person objects to be deleted if they are related to at least one Car object. All of the Car objects which reference a Person object should be deleted first. And then the Person Object can be deleted.



Got any Django Question?