我正在尝试创建一个学校管理系统,在该系统中,可以在数据库中添加新学生(以及以后的教师(的超级用户也必须输入学生的课程。然而,我想将验证用于不同的目的:
-
学生需要从英语和数学字段中选择至少1个选项(如果保持原样,则不需要任何进一步验证(
-
学生需要至少选修1门科学,最多选修2->需要验证以确保课程不会重复。
-
学生可以选择科学、艺术和社会三门课程中的任意一门,但不能两次选修同一门课程。
如果这个问题很愚蠢,或者在我3天前开始学习django和html以完成一个学校项目时,代码中有任何错误,我深表歉意。我阅读了django文档,希望得到答案,但我找不到我想要的东西。
class Student(models.Model):
student_number = models.PositiveIntegerField()
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
class English(models.TextChoices):
LANGLIT = 'LL', _('Language and literature')
LIT = 'L', _('Literature')
english = models.CharField(max_length=2, choices=English.choices, default=English.LANGLIT)
class Math(models.TextChoices):
AA = 'AA', _('Analysis & Approaches')
AI = 'AI', _('Analysis & Interpretation')
math = models.CharField(max_length=2, choices=Math.choices, default=Math.AA)
class Language(models.TextChoices):
FRENCH = 'F', _('French')
SPANISH = 'S', _('Spanish')
ARABIC = 'A', _('Arabic')
MANDARIN = 'M', _('Mandarin')
language = models.CharField(max_length=1, choices=Math.choices, default=Language.FRENCH)
class Science(models.TextChoices):
BIOLOGY = 'BIO', _('Biology')
CHEMISTRY = 'CHEM', _('Chemistry')
PHYSICS = 'PHY', _('Physics')
COMPUTERSCIENCE = 'CS', _('Computer Science')
DESIGNTECHNOLOGY = 'DT', _('Design Technology')
ESS = 'ESS', _('Environmental Systems and Societies')
science = models.CharField(max_length=4, choices=Science.choices, default=Science.BIOLOGY)
class Society(models.TextChoices):
MANAGEMENT = 'BM', _('Business Management')
ECONOMICS = 'ECON', _('Economics')
GEOGRAPHY = 'GEO', _('Geography')
GLOBALPOLITICS = 'GP', _('Global Politics')
HISTORY = 'HIS', _('History')
PSYCHOLOGY = 'PSYCH', _('Psychology')
class Art(models.TextChoices):
VISUALARTS = 'VA', _('Visual Arts')
MUSIC = 'MUS', _('Music'),
FILM = 'FILM', _('Film')
def __str__(self):
return f'{self.first_name} {self.last_name}'
您可以使用ValidationError并应用任何您想要的逻辑
示例:
from django.core.exceptions import ValidationError
def validate_mail(value):
if "@mail.com" in value:
return value
else:
raise ValidationError("This field accepts mail only")
class MailModel(models.Model):
mail = models.CharField(
max_length = 200,
validators =[validate_mail]
)