2👍
✅
Try editing the save method like this,
def save(self, *args, **kwargs):
try:
Attn.objects.get(emp_id=self.emp_id, date=self.date, type='N')
try:
exit = Attn.objects.get(emp_id=self.emp_id, date=self.date, type=='X')
exit.delete()
except Attn.DoesNotExist:
self.type = 'X'
else:
self.type = 'X'
except Attn.DoesNotExist:
self.type = 'N'
return super(Attn, self).save(*args, **kwargs)
Remove the unique_together constraint, its not needed now, you are explicitly overriding the save method and restricting the app to save objects with the conditions above..
EDIT
From the docs,
The ValidationError raised during model validation when the constraint is violated has the unique_together error code.
That means, if the unique_together constraint is violated then, the ValidationError is raised in the model validation itself. Django never even try to reach near the save method, if the constraint is failed. Thus, django-admin raises error before committing the object to the database.
Source:stackexchange.com