Django Вычисление даты
Модель:
class JobCycle(models.Model):
dateReceived = models.DateField(blank=True, null=True)
dueDate = models.DateField(blank=True, null=True)
dateOut = models.DateField(blank=True, null=True)
fee = models.IntegerField(blank=True, null=True)
def __str__(self):
return "Job Cycle" + str(self.id)
def save(self, *args, **kwargs):
if self.dateReceived and self.dueDate:
if self.dateReceived > self.dueDate:
raise ValidationError(
'Due date will never be greater than the received date')
super(JobCycle, self).save(*args, **kwargs)
Я хочу сделать расчет, чтобы срок исполнения никогда не превышал дату получения. Я хочу сделать это в модели
Вы можете переопределить метод сохранения модели save():
Перед или после def __str__
(на том же уровне) добавьте:
def save(self, *args, **kwargs):
if self.dueDate > self.dateReceived:
raise ValidationError("dueDate must never be later than dateReceived!")
super(JobCycle, self).save(*args, **kwargs)
Или, вместо того, чтобы выдать ошибку, вы можете исправить dueDate:
self.dueDate = self.dateReceieve
Зависит от требуемой логики.
Ошибка валидации происходит из:
from django.core.exceptions import ValidationError
You can override the .clean() method [Django-doc] for this:
class JobCycle(models.Model):
dateReceived = models.DateField(blank=True, null=True)
dueDate = models.DateField(blank=True, null=True)
# ...
def clean(self):
super().clean()
if self.dateReceived and self.dueDate and self.dueDate < self.dateReceived:
raise ValidationError('Due date cannot be before received date')
This thus renders the model invalid if the due date lies before the received date.
It might however be better to use a DurationField [Django-doc] here, and store a duration instead. For example with:
from django.db.models import DurationField
class JobCycle(models.Model):
dateReceived = models.DateField(blank=True, null=True)
duration = models.DurationField()
# ...
then the due date is simply self.dateReceived + self.duration, and there is no need to validate that.
Note: The save(..) method is not the place to perform validation. The clean(..) method is for that. The save(..) method is to persist the model in the database.