我正在使用Django 2.0
我有一个带有两个datetime
字段的模型
class AmountGiven(models.Model):
amount = models.FloatField(help_text='Amount given to the contact')
_given_date = models.DateTimeField(
db_column='given_date',
default=datetime.now,
)
promised_return_date = models.DateTimeField(
blank=True,
default=None,
null=True,
)
@property
def given_date(self):
return self._given_date
@given_date.setter
def given_date(self, value):
self._given_date = value
def clean(self):
print(self.given_date)
if self.given_date:
if self.given_date.date() > datetime.today().date():
raise ValidationError({
'given_date': _('The given date was in the future')
})
if self.given_date and self.promised_return_date:
if self.given_date > self.promised_return_date:
raise ValidationError({
'promised_return_date': _('Promised return date can not be earlier than given date')
})
我必须对given_date
和promised_return_date
进行以下验证
given_date
不在将来- 如果
promised_return_date
一世。promised_return_date
不是过去的given_date
我正在使用mixer
生成模型数据
test_models.py
@pytest.mark.django_db
class TestAmountGiven(TestCase):
def test_model_add_amount_given_in_future(self):
amount_given_in_future_1_day = mixer.blend(
'transactions.AmountGiven',
given_date=datetime.now(get_localzone()) + timedelta(days=1),
promised_return_date=datetime.now(get_localzone()) + timedelta(days=300)
)
self.assertRaises(ValidationError, amount_given_in_future_1_day.clean)
assert str(amount_given_in_future_1_day) == str(amount_given_in_future_1_day.amount), \
'__str__ should return amount string'
但是此测试未返回ValidationError
或任何错误。