[PYTHON] Django Foreign Key on_delete argument

reference

Django Official stackoverflow

Foreign Key on_delete behavior

on_delete is when the referencing object is deleted Decide whether to delete or keep the object !!

models.py


#Sample model
class Book(AbstractModel):
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

models.CASCADE When the referenced object (eg Publisher) is deleted Delete an object (eg Book) together Example: If you delete a blog article, you don't need the comments sent to it, so delete it.

models.PROTECT Even if the referenced object (eg Publisher) is deleted Do not delete objects (eg Book) If you want to delete all the objects, you have to do it all manually.

models.SET_NULL When the referenced object (eg Publisher) is deleted Object (eg Book) is set to NULL (eg establish is NULL) Example: This can be used when deleting a user and wanting to keep only the comments that the user has sent to the blog anonymously.

models.SET_DEFAULT When the referenced object (eg Publisher) is deleted The value set in default (example: default in establishment) is set in the object (example: Book)

models.py


publisher = models.ForeignKey(Publisher, on_delete=models.SET_DEFAULT, default='unknown')

models.SET Substitute your own set value. Pass a callable.

models.py


def get_publisher():
    #For the time being, look back at the first one
    return Publisher.objects.all().first()

class Book(AbstractModel):

    publisher = models.ForeignKey(Publisher, on_delete=models.SET(get_publisher))

models.RESTRICT

models.py


class Artist(models.Model):
    name = models.CharField(max_length=10)

class Album(models.Model):
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)

class Song(models.Model):
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    album = models.ForeignKey(Album, on_delete=models.RESTRICT)

console


artist_one = Artist.objects.create(name='artist one')
album_one = Album.objects.create(artist=artist_one)
song_one = Song.objects.create(artist=artist_one, album=album_one)
album_one.delete()
# Raises RestrictedError.
#Error because the song you are referencing exists


artist_two = Artist.objects.create(name='artist two')
album_two = Album.objects.create(artist=artist_two)
song_two = Song.objects.create(artist=artist_one, album=album_two)
# artist_Note that you are using one
artist_two.delete()
# Raises RestrictedError.
# artist_If you delete two, the album that is CASCADE will also be deleted, so
#An error occurs in the referenced Song

Recommended Posts

Django Foreign Key on_delete argument
Write foreign key constraints in Django
Django Foreign Key Tutorial Ends in 10 Minutes
Django 1.4.2 session key generation
Foreign Key in Python SQLite [Note]