【问题标题】:How to Update a Many-Many Field in Django [duplicate]如何在 Django 中更新多对多字段
【发布时间】:2013-06-22 04:10:18
【问题描述】:

在我的 django 应用中,我的模型如下所示:

class Tag(models.Model):
    title = models.CharField(max_length=50,)

class Publication(models.Model):
    title = models.CharField(max_length=200,)
    tags = models.ManyToManyField(Tag, blank=True, related_name="publications", null=True)

假设我的标签表中有 2 个标签:“狗”和“猫”。假设我现有的出版物“宠物”上只有“狗”标签。如何将现有的“猫”标签添加到“宠物”?

在 Django 文档https://docs.djangoproject.com/en/dev/ref/models/instances/ 中,我看到了以下用于更新数据库项的示例:

product.name = 'Name changed again'
product.save(update_fields=['name'])

但我没有看到任何更新多对多字段的内容。我该怎么做?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:
    # let publication be your existing Pets publication instance
    cats_tag, created = Tag.objects.get_or_create(title='cats')
    publication.tags.add(cats_tag)
    

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2016-08-17
      • 2022-08-10
      • 1970-01-01
      相关资源
      最近更新 更多