Django: delete all m2m relationships

if I have two simple models:

class Tag(models.Model): name = models.CharField(max_length=100) class Post(models.Model): title = models.CharField(max_length=100) tags = models.ManyToManyField(Tag, blank=True) 

given a Post object with a series of add ed tags, I know that I need to remove any of them, but how to do a bulk removal (delete everything)? Thanks

+6
django
source share
2 answers

Have you tried Post.tags.clear() ?

+21
source share

If you need to remove only the relationship for the entire instance between the two models, you can do this by contacting the Relationship Table Manager. The m2m link table can be accessed through MyModel.relations.through , so it becomes easier to remove links:

 MyModel.relations.through.objects.all().delete() 

link:

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through

-3
source share

All Articles