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()
"MyModel item with same foobar field exist on site %r" % site
return super(MyModel, self).save(*args, **kwargs)
#unique_together = ("foobar", "site") # unique_together doesn't work with ManyToMany!
# See: http://code.djangoproject.com/ticket/702