django - 如何仅删除 m2m 关系?

标签 django django-models django-orm

模型:

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 个特定关系。

最佳答案

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

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

如果您愿意,也可以直接访问直通表:
Province.user.through.objects.get(province__id=3, user__id=4).delete()

关于django - 如何仅删除 m2m 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5247654/

相关文章:

python - 来自 manage.py runserver 的堆栈跟踪没有出现

Django:获取相关对象的相关对象并传递给模板

python - 我在settings.py上实现了电子邮件设置,但是当我提交表单时它不起作用

python - 通过正确使用 ManyToMany 来处理 django 中的复杂模型

python - Django查询和终端中原始sql查询之间的执行时间差异

Django:在字段上与在不同模型上存储模型属性

Django 开发服务器消息 - 它们是什么意思?

django - Django 有 SmallIntegerField 的原因是什么?

Django : Get specific columns from multiple tables

Django ORM : caching and manipulating ForeignKey objects