I need to check the model field for a list of available items before I save them to the database.
models.py
class Vendors(models.Model):
COUNTRY_CHOICES = tuple(countries)
...
country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
...
class for saving models
class CsvToDatabase(APIView):
def post(self, request, format=None):
data = request.data
for key, vendor in data.items():
Vendors(
...,
country=vendor['Country'],
...,
).save()
return Response({'received data': request.data,
'message': 'Vendors from vendors_list were successfully added to the database'})
For validation Im added clean method to models
def clean(self):
if self.country not in [x[1] for x in countries]:
raise ValidationError(detail="Country name does not match to the country list ")
But it doesnt work
Next step I added the same code to method save
def save(self):
if self.country not in [x[1] for x in countries]:
raise ValidationError(detail="Country name does not match to the country list ")
And it works, but I read that using validation in the save method is not correct. And the correct method for use - clean, why in my case it does not work?
clean(), however theclean()method on a model isn't called automatically. It gets called when you clean aModelFormfor the model (by checkingform.is_valid()) or when you validate aModelSerializer. You can also just call it yourself. Create theVendorsobject, callfull_clean()first (and catch the ValidationError) and only after that callsave(). Note: if you callfull_clean(), the model will already validate that the country is set correctly, you don't need to add that inclean().