django - unique_together constraint on multiple columns with NULL values -



django - unique_together constraint on multiple columns with NULL values -

i have database of automotive parts includes branded & unbranded items. if brand name unavailable, full_name part.name, else brand.name + part.name.

how can define unique_together constraint ensure uniqueness of full_name @ database level? current constraint allows multiple parts same name if brand name missing (i.e. brand_id foreignkey null)

class brand(models.model): name = models.charfield(max_length=100) class part(models.model); name = models.charfield(max_length=100) brand = models.foreignkey(brand, null=true, blank=true) def get_full_name(self): if self.brand_id: full_name = '%s %s'.format(self.brand.name, self.name) else: full_name = self.name homecoming full_name class meta: unique_together = (('name', 'brand'),)

using : django 1.6 + postgresql 9.3

p.s. there's first-class suggestion here accomplish sql. i'm looking solution using django orm. http://stackoverflow.com/a/8289253/781695

there's no way tell django add together index i'm afraid, unique_together handles simple indexes. however, can validate @ model layer using clean method:

from django.core.validators import validationerror class part(models.model); ... def clean(self): duplicates = part.objects.exclude(pk=self.pk).filter(name=self.name) if self.brand: duplicates = duplicates.filter(brand=self.brand) if duplicates.count(): raise validationerror(u'duplicate part/brand')

you may want manually add together index postgres database, additional info security.

django postgresql django-models

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -