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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 1 month ago
  2. Python Django CRUD Example Tutorial by tuts_station 1 month, 2 weeks ago
  3. Browser-native date input field by kytta 2 months, 4 weeks ago
  4. Generate and render HTML Table by LLyaudet 3 months, 1 week ago
  5. My firs Snippets by GutemaG 3 months, 1 week 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.