开发者

Django: remove all m2m relations

开发者 https://www.devze.com 2023-01-01 07:12 出处:网络
if I have two simple models: class Tag(models.Model): 开发者_开发百科name = models.CharField(max_length=100)

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


Have you tried Post.tags.clear()?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消