问题
I have the following Django model:
class Customer(models.Model):
email = models.EmailField(unique=True)
In my testcase, I instantiate it without an e-mail.
class CustomerTestCase(TestCase):
def test_that_customer_can_be_created_with_minimum_data(self):
customer = Customer.objects.create()
print(customer.__dict__)
I expect it to raise an error, but it creates a record with an empty field email
. The same thing happens if I explicitly say null=False
and blank=False
. Instead, it just prints the empty email.
{'email': ''}
What am I missing?
回答1:
You're missing the fact that validation is not run on save - see the validation docs:
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.
As that doc implies, usually validation is carried out in the context of a form.
来源:https://stackoverflow.com/questions/44101172/required-field-in-django-model-not-mandatory