robos85
robos85

Reputation: 2554

How to delete ONLY m2m relation?

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 relation when I know user_id and province_id? If i user delete() method it also removes province and I want to avoid it. I can't find anywhere how to delete 1 specific relation in m2m field.

Upvotes: 3

Views: 4141

Answers (3)

rom
rom

Reputation: 3672

I know this question is old... If you want to delete all the users of a specific province:

province.user.clear()

Upvotes: 1

Rachid
Rachid

Reputation: 2589

If you need to delete only the relationship for all instance between 2 models then you can do that by accessing the Manager of the relationship table. The m2m relationship table can be accessed via MyModel.relations.through so for deleting the relationships it becomes easy:

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

reference:

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

Upvotes: 1

Use the remove method on your ManyToMany manager.

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

You can also access the through table directly if you so desire:

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

Upvotes: 10

Related Questions