Login

simple unique_together check with M2M field

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

Comments

Please login first before commenting.