Django:在保存模型之前检查多个条件

时间:2019-06-21 09:43:53

标签: python django model save

这是我的模型。py:

class Department(models.Model):
name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Department')

def __str__(self):
    return '{}'.format(self.name)

class Users(models.Model):
name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Name')
last_name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Last Name')
department = models.ForeignKey(Department, related_name='user_department', on_delete=models.CASCADE)

def __str__(self):
    return '{} {} - {}'.format(self.name, self.last_name, self.department)

class WeeklyCheck(models.Model):
department = models.ForeignKey(Department, related_name='weeklycheck_department', on_delete=models.CASCADE)
start_date = models.DateField(blank=False, null=True, verbose_name='Start date')
end_date = models.DateField(blank=False, null=True, verbose_name='End Date')
active = models.BooleanField(default=True, verbose_name='Active?')

def __str__(self):
    return '{} / {} to {} - {}'.format(self.department, self.start_date, self.end_date, self.active)

class Attendance(models.Model):
user = models.ForeignKey(Users, related_name='attendance_user', on_delete=models.CASCADE)
date = models.DateField(blank=False, null=True, verbose_name='Date')
check = models.BooleanField(default=True, verbose_name='Check')

def __str__(self):
    return '{} / {} / {}'.format(self.user, self.date, self.check)

def clean(self):
    qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True)
    department_a = Users.objects.filter(department__name='Department A')
    if not qs and department_a:
        qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True)
        department_b = Users.objects.filter(department__name='Department B')
        if not qs and department_b:
            qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True)
            department_c = Users.objects.filter(department__name='Department C')
            if not qs and department_c:
                raise ValidationError('You can not check! The week is not active.')

我有部门(部门)拥有用户(用户)。 每个部门都标记了具有开始日期和结束日期的周( WeeklyCheck ),这些周可能处于活动状态,也可能不处于活动状态。 每个用户都检查某个日期(出勤)。

我想要的是,根据您部门的事先任命,他可以或不能执行验证。

我使用了干净的方法,但是没有结果,因为不管部门是什么,它都只有一个活跃的星期,它接受验证。

0 个答案:

没有答案