gpt4 book ai didi

python - 添加 Django 模型约束?

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:46 26 4
gpt4 key购买 nike

我的模型 Period 如下:

class Period(models.Model):
number = models.PositiveIntegerField(primary_key=True)
start_time = models.TimeField()
end_time = models.TimeField()

我如何添加约束来制作Period.start_time < Period.end_time和 Period 模型有这样的顺序吗?

Period 1: 7:00-7:50; Period 2: 7:50-8:40; ...

字段编号表示周期实例的顺序。我的方法是添加方法来检查它是否有效。但是,我想知道有什么数据库方法可以做到这一点。

最佳答案

你可以通过多种方式做到这一点

方法-1:重写Period模型的save()方法为

<b>from django.core.exceptions import ValidationError</b>


class Period(models.Model):
number = models.PositiveIntegerField(primary_key=True)
start_time = models.TimeField()
end_time = models.TimeField()

<b>def save(self, *args, **kwargs):
if self.end_time < self.start_time:
raise ValidationError("some message")
super().save(*args, **kwargs)</b>



方法-2:重写模型的clean()方法

<b>from django.core.exceptions import ValidationError</b>


class Period(models.Model):
number = models.PositiveIntegerField(primary_key=True)
start_time = models.TimeField()
end_time = models.TimeField()

<b>def clean(self):
super().clean() # calling default cleaning
if self.end_time < self.start_time:
raise ValidationError("some message")</b>


方法- 3:覆盖full_clean()方法

<b>from django.core.exceptions import ValidationError</b>


class Period(models.Model):
number = models.PositiveIntegerField(primary_key=True)
start_time = models.TimeField()
end_time = models.TimeField()

<b>def full_clean(self, exclude=None, validate_unique=True):
super().full_clean(exclude=None, validate_unique=True) # calling default full_clean
if self.end_time < self.start_time:
raise ValidationError("some message")</b>



引用
1. Model.clean() - Django doc
2. Model.save() - Django doc
3. Model.full_clean() - Django doc

关于python - 添加 Django 模型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52268509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com