【问题标题】:How to delete ONLY m2m relation?如何仅删除 m2m 关系?
【发布时间】:2011-03-09 15:00:54
【问题描述】:

型号:

class Province(models.Model):
    user = models.ManyToManyField(User, blank=True)
    name = models.CharField(max_length=30, unique=True)

class City(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, editable=False, unique=False)
    ownership = models.ManyToManyField(User, through='UserCity')


class UserCity(models.Model):
    user = models.ForeignKey(User)
    province = models.ForeignKey(Province)
    city = models.ForeignKey(City)


class District(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True, editable=False)
    ownership = models.ManyToManyField(User, through='UserDistrict')

class UserDistrict(models.Model):
    user = models.ForeignKey(User)
    province = models.ForeignKey(Province)
    city = models.ForeignKey(City)
    district = models.ForeignKey(District)

当我知道user_id 和province_id 后如何删除关系?如果我使用 delete() 方法,它也会删除省,我想避免它。我在任何地方都找不到如何删除 m2m 字段中的 1 个特定关系。

【问题讨论】:

    标签: django django-models django-orm


    【解决方案1】:

    我知道这个问题很老... 如果要删除特定province的所有users

    province.user.clear()
    

    【讨论】:

      【解决方案2】:

      在您的 ManyToMany 经理上使用 remove 方法。

      Province.objects.get(id=3).user.remove(user_id)
      

      如果您愿意,也可以直接访问直通表:

      Province.user.through.objects.get(province__id=3, user__id=4).delete()
      

      【讨论】:

      • 谢谢 - 这两种方法都有效。正如我所看到的,它并没有删除我声明的任何其他关系 - 城市 - 省,城市 - 区。我想我必须手动完成。
      • NP:还有问题吗?我以为你特别不想删除其他关系?
      • 呵呵,我想删除所有基于描述的关系。当我删除省用户关系时,我希望删除所有其他关系。我更新了我的帖子,我的所有表格都有了。是否可以自动删除其他关系或我必须手动删除?
      • 您必须使用自定义函数删除其他人,该函数采用 user_id 并删除它需要的内容。
      【解决方案3】:

      如果您只需要删除 2 个模型之间所有实例的关系,则可以通过访问关系表的管理器来执行此操作。 m2m 关系表可以通过MyModel.relations.through 访问,因此删除关系变得很容易:

      MyModel.relations.through.objects.all().delete()
      

      参考:

      https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-17
        • 1970-01-01
        • 1970-01-01
        • 2019-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多