Login

unique_together with many to many fields

Author:
j4nu5
Posted:
September 21, 2011
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

ashishnetworks (on January 22, 2016):

This is really awesome way but it raises error in separate page of Exception handling. isn't there any way so that even this custom error could be displayed over page the form where input data would be taken.

In other words how can I display this error on same page of form

#

seanchon (on December 19, 2017):

This is rad! It took me a while to figure out how to create integrity checks on the many-to-many add method, and this was a huge relief to find. Thank you!

#

Please login first before commenting.