Login

simple unique_together check with M2M field

Author:
jedie
Posted:
August 7, 2009
Language:
Python
Version:
1.1
Tags:
unique_together manytomany
Score:
-2 (after 4 ratings)

unique_together doesn't work with ManyToMany, yet. See: http://code.djangoproject.com/ticket/702

Here a simple test in save() that would raise a IntegrityError.

 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
class MyModel(models.Model):
    site = models.ManyToManyField(Site)
    on_site = CurrentSiteManager()
    
    foobar = ... # A unique field
    
    def save(self, *args, **kwargs):
        if self.id == None: # new item should be created.
            # manually check a unique togeher, because django can't do this with a M2M field.
            # Obsolete if unique_together work with ManyToMany: http://code.djangoproject.com/ticket/702
            exist = MyModel.on_site.filter(foobar=self.foobar).count()
            if exist != 0:
                from django.db import IntegrityError
                # We can use attributes from this model instance, because it needs to have a primary key
                # value before a many-to-many relationship can be used.
                site = Site.objects.get_current()
                raise IntegrityError(
                    "MyModel item with same foobar field exist on site %r" % site
                )
        
        return super(MyModel, self).save(*args, **kwargs)

    class Meta:
        #unique_together = ("foobar", "site") # unique_together doesn't work with ManyToMany!
        # See: http://code.djangoproject.com/ticket/702

More like this

  1. manually models unique_together check via signals by jedie 5 years, 9 months ago
  2. unique_together with many to many fields by j4nu5 3 years, 6 months ago
  3. Limit ManyToMany fields in forms by jedie 5 years, 8 months ago
  4. Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance by bikeshedder 7 years, 10 months ago
  5. jQuery Double Click Edit ManyToMany in Admin by justhamade 5 years, 2 months ago

Comments

Please login first before commenting.