I was worried about on_delete when I tried to set a foreign key in Django, so I summarized it.
I'm currently building a web app to hold game tournaments, so I needed a table to connect the tournament with the participants.
So I created a model in which the participant table has a tournament table and a user table with foreign keys.
models.py
from django.db import models
from django.contrib.auth.models import User
from games.models import Game
class Participations(models.Model):
Game = models.ForeignKey(Game)
User = models.ForeignKey(User)
The following error occurs during migration
Traceback (most recent call last):
Game = models.ForeignKey(Game)
TypeError: __init__() missing 1 required positional argument: 'on_delete'
I got angry without on_delete.
The cause is simple, but it is because on_delete is not specified in the argument.
By the way, it seems that it became mandatory from Django 2.0.
When I actually look at the official release notes, it says like this.
The on_delete argument for ForeignKey and OneToOneField is now required in models and migrations.
** Translate ** The ForeignKey and OneToOneField on_delete arguments are now required for modeling and migration.
So what is on_delete?
This is the behavior when the referenced object is deleted.
https://docs.djangoproject.com/ja/3.0/ref/models/fields/
Below is a brief summary based on the official reference
on_delete=models.CASCADE Ze that deletes all foreign key data!
on_delete=models.PROTECT Ze that makes it impossible to delete!
on_delete=models.SET_NULL If it's deleted, I'll put NULL instead! Set null = true when using this Ze!
on_delete=models.SET_DEFAULT Ze to replace the default value when deleted!
on_delete=models.SET(hogehoge) If it is deleted, you can call a function etc. and enter an arbitrary value Ze!
on_delete=models.DO_NOTHING Do nothing Ze!
It's a rich migration life with on_delete that suits your purpose Ze!
Recommended Posts