How to protect objects from being deleted in ManyToManyField() relationship ?

I have many-to-many relationship between models Article and Tag (model Article has field tags) - see the code:

class Tag(models.Model):
    name = models.CharField(max_length=30, default='None')

class Article(models.Model):
    title = models.CharField(max_length=250)
    published_at = models.DateTimeField(default=timezone.now())
    tags = models.ManyToManyField(Tag, blank=True)

Now if I want to delete Tag instance, then also all related Article instances will be deleted.

How to protect Article instances ?

In ForeignKey I know I can use on_delete=models.SET_NULL - is it possible to use also something similar for ManyToManyField() ?

Thank you.

1 Like

That’s not the default behaviour. If you delete a Tag, the Article should still exist.

Take a look at Django m2m examples, specifically the section that says If we delete a Publication , its Articles won’t be able to access it:

1 Like

@marcorichetta Yes, you are right about that.
But I’m trying to delete Tag instance using Django Admin.
So then it seems it is Django Admin that is enforcing deletion of related items - I’m getting Are you sure you want to delete the selected tags? All of the following objects and their related items will be deleted:.
Is there something I can do in Django Admin to let me just delete Tag but leave the Article instance still available ?

I can’t recreate the behavior you’re describing from the information you’ve provided here. When I go to the “Tag” admin page and go to delete a tag, it tells me it’s going to delete the tag and the tag-article relationship. There is no indication on that page that the Article will be deleted; and when the Tag is deleted, the articles remain.

2 Likes

I re-did and re-tested now from scratch and you are right. I don’t know what did I do wrong last time. Sorry both for wasting your time on such easy point.