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
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.
- [Django]-Django-pyodbc SQL Server/freetds server connection problems on linux
- [Django]-Django Test – South migration reports 'no such table' but I can see said table in the db
- [Django]-Django Rest Framework error: {"user":["This field is required."]
- [Django]-Create method for foreign key relationships with Django Rest Framework serializers
Source:stackexchange.com