Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all relations from manytomany?

Tags:

django

In one model, I have this:

class MyModel(models.Model):     relations = models.ManyToManyField(OtherModel)     .... 

and if I choose:

my_object.relations.remove(other_model_object) 

it works.

How to remove all objects from the relations? my_object.relations.clean() is not working.

like image 856
Nips Avatar asked Aug 29 '11 12:08

Nips


People also ask

How do you get rid of a many to many relationship?

To avoid this problem, you can break the many-to-many relationship into two one-to-many relationships by using a third table, called a join table. Each record in a join table includes a match field that contains the value of the primary keys of the two tables it joins.

How do I delete a Queryset in Django?

The django querysets where we use filter() function to select multiple rows and use delete() function to delete them is also known as bulk deletion.


2 Answers

First, you'll need to clear the relationship(s) by using .clear() or .remove(), whichever suits your needs better according to the docs.

After that, you'll need to delete the object(s) by using the [YourModel].delete() method.

like image 52
Brandon Avatar answered Sep 23 '22 05:09

Brandon


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

like image 30
Rach Avatar answered Sep 21 '22 05:09

Rach