Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: remove all m2m relations

Tags:

django

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 number of Tags added to it, I know hot to remove any of them, but how to do a mass remove (remove all)? Thanks

like image 777
pistacchio Avatar asked May 26 '10 14:05

pistacchio


People also ask

How do I delete a many-to-many relationship in Django?

ManyToMany field has some methods that you can call: add(Object) remove(Object) clear() this one is for removing all objects.

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 to implement many-to-many relationship in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.publications.add(p1) Traceback (most recent call last): ...

How fetch data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.


1 Answers

Have you tried Post.tags.clear()?

like image 87
Mike DeSimone Avatar answered Oct 07 '22 20:10

Mike DeSimone