Last modified: Jan 10, 2023 By Alexander Williams

Django on_delete=models.cascade (Examples)

"on_delete=models.cascade" meaning

is the behaviour to adopt when the referenced object is deleted. It is not specific to django, this is an SQL standard.

Example 1


class Track(models.Model):
    album = models.ForeignKey(Album, related_name='tracks')
    album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
    order = models.IntegerField()
    title = models.CharField(max_length=100)
    duration = models.IntegerField()

Example 2


class Group(models.Model):
    # Table Column Fields
    name = models.CharField(max_length=128)
    group_country = models.ForeignKey(Country, models.CASCADE)
    members = models.ManyToManyField(Person, related_name='groups', through='Membership')

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

Example 3


class Friendship(models.Model):
    # Table Column Fields
    from_friend_country = models.ForeignKey(Country, models.CASCADE, related_name="from_friend_country")
    from_friend_id = models.IntegerField()
    to_friend_country_id = models.IntegerField()
    to_friend_id = models.IntegerField()

    # Relation Fields
    from_friend = models.ForeignObject(
        Person,
        on_delete=models.CASCADE,
        from_fields=['from_friend_country', 'from_friend_id'],
        to_fields=['person_country_id', 'id'],
        related_name='from_friend',
    )

    to_friend_country = models.ForeignObject(
        Country,
        from_fields=['to_friend_country_id'],
        to_fields=['id'],
        related_name='to_friend_country',
        on_delete=models.CASCADE,
    )

    to_friend = models.ForeignObject(
        Person,
        from_fields=['to_friend_country_id', 'to_friend_id'],
        to_fields=['person_country_id', 'id'],
        related_name='to_friend',
        on_delete=models.CASCADE,
    )