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 7 years ago
  2. Validation for 'unique' and 'unique_together' constraints (different version) by miracle2k 9 years, 1 month ago
  3. manually models unique_together check via signals by jedie 7 years, 1 month ago
  4. TrueNoneField by diverman 6 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 9 years, 3 months ago

Comments

ashishnetworks (on January 22, 2016):
<p>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.</p> <p>In other words how can I display this error on same page of form</p>

#

Please login first before commenting.