Login

unique_together with many to many fields

Author:
j4nu5
Posted:
September 21, 2011
Language:
Python
Version:
Not specified
Tags:
unique_together m2m-manytomanyfield many-to-many-field
Score:
0 (after 0 ratings)

To use it, append all your model save methods with a IntegrityError catcher.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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 Publisher(models.Model):
    name = models.CharField(max_length=30)

class Book(models.Model):
    """
    A Book may have multiple publishers.
    But a two books cannot have same name and a common publisher.
    
    """
    name = models.CharField(max_length=30)
    publishers = models.ManyToManyField(Publisher)

@receiver(m2m_changed, sender=Book.publishers.through)
def verify_uniqueness(sender, **kwargs):
    book = kwargs.get('instance', None)
    action = kwargs.get('action', None)
    publishers = kwargs.get('pk_set', None)

    if action == 'pre_add':
        for publisher in publishers:
            if Book.objects.filter(name=book.name).filter(publishers=publisher):
                raise IntegrityError('Book with name %s already exists for publisher %s' % (book.name, Publisher.objects.get(pk=publisher)))

More like this

  1. simple unique_together check with M2M field by jedie 5 years, 12 months ago
  2. Validation for 'unique' and 'unique_together' constraints (different version) by miracle2k 8 years ago
  3. manually models unique_together check via signals by jedie 6 years ago
  4. TrueNoneField by diverman 5 years, 8 months ago
  5. Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance by bikeshedder 8 years, 2 months ago

Comments

Please login first before commenting.