Better management of unique constraint for Part

This commit is contained in:
Oliver 2021-06-22 09:33:07 +10:00
parent 40fcfe1f47
commit a38835022a
2 changed files with 20 additions and 19 deletions

View File

@ -0,0 +1,17 @@
# Generated by Django 3.2.4 on 2021-06-21 23:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('part', '0067_partinternalpricebreak'),
]
operations = [
migrations.AddConstraint(
model_name='part',
constraint=models.UniqueConstraint(fields=('name', 'IPN', 'revision'), name='unique_part'),
),
]

View File

@ -321,6 +321,9 @@ class Part(MPTTModel):
verbose_name = _("Part") verbose_name = _("Part")
verbose_name_plural = _("Parts") verbose_name_plural = _("Parts")
ordering = ['name', ] ordering = ['name', ]
constraints = [
UniqueConstraint(fields=['name', 'IPN', 'revision'], name='unique_part')
]
class MPTTMeta: class MPTTMeta:
# For legacy reasons the 'variant_of' field is used to indicate the MPTT parent # For legacy reasons the 'variant_of' field is used to indicate the MPTT parent
@ -642,23 +645,6 @@ class Part(MPTTModel):
'IPN': _('Duplicate IPN not allowed in part settings'), 'IPN': _('Duplicate IPN not allowed in part settings'),
}) })
# Part name uniqueness should be case insensitive
try:
parts = Part.objects.exclude(id=self.id).filter(
name__iexact=self.name,
IPN__iexact=self.IPN,
revision__iexact=self.revision)
if parts.exists():
msg = _("Part must be unique for name, IPN and revision")
raise ValidationError({
"name": msg,
"IPN": msg,
"revision": msg,
})
except Part.DoesNotExist:
pass
def clean(self): def clean(self):
""" """
Perform cleaning operations for the Part model Perform cleaning operations for the Part model
@ -671,8 +657,6 @@ class Part(MPTTModel):
super().clean() super().clean()
self.validate_unique()
if self.trackable: if self.trackable:
for part in self.get_used_in().all(): for part in self.get_used_in().all():