[Django]-How to prevent duplicate entries in model from django admin

8👍

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
👤Nikita

2👍

Do you mean having two or more instances with same asset_code AND status is ok as long as only one has status=1 ? Or that the combination of asset_code and status should be unique ? If the second, it’s quite simple:

class Verification(models.Model):
    # your fields here 
    class Meta:
        unique_together = [("asset_code", "status)]

The first case (which would be a rather strange requirement but anyway…) is more involved, you either need a trigger in the database or some custom validation in the model, cf https://docs.djangoproject.com/en/1.6/ref/models/instances/#django.db.models.Model.validate_unique

Oh and yes: if you only want to prevent this in the admin, you should instead provide your own ModelForm for the ModelAdmin and write your validation in the form’s clean method.

Leave a comment