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 add
ed to it, I know hot to remove any of them, but how to do a mass remove (remove all)? Thanks
ManyToMany field has some methods that you can call: add(Object) remove(Object) clear() this one is for removing all objects.
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.
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): ...
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.
Have you tried Post.tags.clear()
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With