How to remove all items from a Many-to-Many relation in Django?

Asked

Viewed 302 times

0

I have the following models in my Django app:

class Tag(models.Model):
    name        = models.CharField(max_length=150)
    description = models.TextField(null=True, blank=True)
    created_at  = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tags'
        ordering = ('name', )


class Question(models.Model):
    title = models.CharField(max_length=300)
    text  = models.TextField()
    user  = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='questions')
    tags  = models.ManyToManyField(Tag, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

In the case, Question has N relationships with N tags. Suppose in Question 1 I have a relationship with tags 1, 2 and 3, as I would to remove all tags related to Question?

Example:

 question = Question.objects.get(pk=1)
 # Quero desassociar  todas as tags dessa questão

1 answer

2

To remove all tags related to Django offers the function clear that removes all objects from the set of related objects without deleting the relations only by removing the association, if you want to remove and delete the related objects use the function remove, some examples to clarify the idea

Remove only associations(tags will still exist)

>>> question = Question.objects.get(pk=1)
>>> question.tags.clear()
>>> question.tags.all()
<QuerySet []>
>>> Tag.objects.all()
<QuerySet [<Tag: 1>, <Tag: 2>, <Tag: 3>]>

Delete associations and delete tags (tags will no longer exist)

question = Question.objects.get(pk=1)

# deleta as tags 
for tag in question.tags.all():
    tag.delete()

Tag.objects.all() # retorna <QuerySet []>

I tested the function remove and it didn’t work, so I did this code above to remove manually.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.