如何删除只有m2m的关系?

时间:2011-03-09 15:00:54

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

3 个答案:

答案 0 :(得分:10)

使用ManyToMany经理上的删除方法。

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

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

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

答案 1 :(得分:1)

如果您只需要删除2个模型之间所有实例的关系,那么您可以通过访问关系表的管理器来实现。可以通过MyModel.relations.through访问m2m关系表,以便删除关系变得容易:

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

参考:

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

答案 2 :(得分:1)

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

province.user.clear()