I created a Student model with field choices. However, when I save it, it doesn't validate whether the choice is in the choices I specified in the model field.
Why doesn't it prevent me from saving a new object with a choice I didn't specify in my model?
Here is the model:
class Student(models.Model):
year_in_school = models.CharField(
max_length=4,
choices= [
('FRES', 'Freshman'),
('SOPH', 'Sophomore'),
],
)
And here is the code I wrote in the shell:
>>> from app.models import Student
>>> new_student = Student.objects.create(year_in_school='HACK')
>>> new_student.year_in_school
'HA'
You might want to read more about choices here. The relevant part copied below:
If choices are given, they’re enforced by model validation
Choices are not enforced at the database level. You need to perform model validation (by calling full_clean()
) in order to check it.
full_clean()
will not be called automatically when you call your model’s save()
method. You’ll need to call it manually.