How to remove ONLY m2m ratio?

Model:

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)

How can I delete a relation when I know user_id and province_id? If the user delete () method, I delete the province, and I want to avoid it. I can not find anywhere how to remove 1 specific relation in the m2m field.

+3
source share
3 answers

Use the uninstall method in ManyToMany Manager .

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

You can also access the pivot table if you want:

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

, , . m2m MyModel.relations.through, :

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

:

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

+1

I know this question is old ... If you want to delete everything usersfor a specific province:

province.user.clear()
+1
source

All Articles