[Django]-How to delete ONLY m2m relation?

10👍

✅

Use the remove method on your ManyToMany manager.

Province.objects.get(id=3).user.remove(user_id)

You can also access the through table directly if you so desire:

Province.user.through.objects.get(province__id=3, user__id=4).delete()

1👍

If you need to delete only the relationship for all instance between 2 models then you can do that by accessing the Manager of the relationship table. The m2m relationship table can be accessed via MyModel.relations.through so for deleting the relationships it becomes easy:

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

reference:

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

1👍

I know this question is old…
If you want to delete all the users of a specific province:

province.user.clear()

Leave a comment