[Answered ]-How to ensure uniqueness in manytomany fields in Django

2👍

You don’t need to specify unique_together. The ManyToManyField in Django is unique by default. Try adding the same relationship twice and you will see you have only one record.

There is a useful Django Snippet for this which I’ve modified for your example:

from django.db import models
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from django.db.utils import IntegrityError

class User(models.Model):
    pass

class Tag(models.Model):
    text = models.CharField(unique=True)

class Subscription(models.Model):
    owner = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag)
    class Meta:
        unique_together = (("owner", "tags"),)

class Post(models.Model):
    owner = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag)

@receiver(m2m_changed, sender=Subscription.tags.through)
def verify_uniqueness(sender, **kwargs):
    subscription = kwargs.get('instance', None)
    action = kwargs.get('action', None)
    tags = kwargs.get('pk_set', None)

    if action == 'pre_add':
        for tag in tags:
            if Subscription.objects.filter(owner=subscription.owner).filter(tag=tag):
                raise IntegrityError('Subscription with owner %s already exists for tag %s' % (subscription.owner, tag))

Leave a comment