Search code examples
pythonmysqldjangodjango-formsdjango-validation

How to prevent duplicate entries in model from django admin


I have an application having a model called Verifications. It has fields like: asset_code, Status, Location, Emp_id etc. I can add verifications using "Add Verification" from django admin panel. But I want to restrict adding duplicate asset_code entries (if asset_code already exists).

class Verification(models.Model):
    asset_code = models.CharField(verbose_name="Asset Code",max_length=16, default="")
    scan_time = models.DateTimeField(verbose_name="Time of smartDNA scan",auto_now_add=True,default=datetime.datetime.now)
    credential = models.CharField(verbose_name="smartDNA Credential",max_length=16, default="")
    status = models.IntegerField(verbose_name="Scanning Status",choices=STATUS_CHOICES,default=1)
    operator = models.CharField(verbose_name="Operator",max_length=16, default="")
    location = models.CharField(verbose_name="Branch",max_length=64, default="")
    auth_code = models.CharField(verbose_name="Scanner Authentication",max_length=20, default="DSC(Verisign")
    emp_id = models.CharField(verbose_name="EMP ID",max_length=16, default="")
    image = models.CharField(verbose_name="Image",max_length=24, default="dd")
    created = models.DateTimeField(verbose_name="Created on",blank=True,auto_now_add=True)
    modified = models.DateTimeField(verbose_name="Modified on",blank=True,auto_now=True)
    product_details = models.CharField(verbose_name="Product Details",max_length=64, default="")

Status field can have values between 1 to 10.

How can I prevent add entries in model if asset_code already exist and having status=1.


Solution

  • add unique=True to asset_code field definition

    UPDATE:

    Only for admin:

    admin.py

    from django import forms
    
    class VerificationAdminForm(forms.ModelForm):
        class Meta:
            model = Verification
    
        def clean_asset_code(self):
            asset_code = self.cleaned_data['asset_code']
            if Verification.objects.filter(asset_code=asset_code).exists():
                raise forms.ValidationError("This asset code already exist.")
            return asset_code
    
    class VerificationAdmin(admin.ModelAdmin):
        form = VerificationAdminForm