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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.