Django: How can you validate a model if the __init__() just raises errors as soon as you feed it data?
Let's say I have a CarModel(models.Model)
that uses price = models.DecimalField()
:
import CarModel
car = CarModel(name='Corvette', price='Hello World')
Traceback (most recent call last):
...
ValidationError: 'price needs to be a Decimal()'
The error was basically that.
Since the price was expecting a decimal but received a string, it raises a ValidationError immediately.
I was expecting it to work like this:
car = CarModel(name='Corvette', price='Hello World')
car.full_clean()
Traceback (most recent call last):
...
ValidationError: 'price needs to be a Decimal()'
Im I thinking about this correctly? Does it seem like ValidationError should only be raised 开发者_高级运维on save() or by explicitly calling full_clean()?
Instances are not saved until you do save(). That being said the issue is one init django tries to do proper coercion, turning all your values into the right datatypes. In this case the data can't even be coerced properly, so Django gives you an exception right away. I realize the distinction may seem a bit nebulous, but if it wasn't this way you could be getting a DecimalField off of a model without getting a Decimal object.
精彩评论