我想提出一些错误,例如: 如果用户使用相同的外键创建bus_stop_1和bus_stop_2 或者如果表中对象的数量超过 4
所以我的疑问是,当我使用 clean 方法时,它无法正常工作,如何引发错误
class ConnectedRoute(models.Model):
bus_stop_1 = models.ForeignKey(
BusStop, on_delete=models.CASCADE, related_name='stop1')
bus_stop_2 = models.ForeignKey(
BusStop, on_delete=models.CASCADE, related_name='stop2')
distance = models.FloatField(blank=True, null=True)
time = models.TimeField(blank=True, null=True)
def clean(self):
if self.bus_stop_1 == self.bus_stop_2:
raise ValidationError('Both stop cannot to the same')
count_stop1 = ConnectedRoute.objects.filter(
bus_stop_1=self.bus_stop_1).count()
count_stop2 = ConnectedRoute.objects.filter(
bus_stop_2=self.bus_stop_2).count()
if count_stop1 + count_stop2 > 4:
raise ValidationError('Only 4 connections allowed.')
我尝试使用这种干净的方法,但我从未发现它有用 有什么遗漏的吗
您必须调用 model_instance.save() 来调用 clean() 方法进行验证,或者可以手动调用 model_instance.clean() 然后 model_instance.save()
尝试重写save方法并在save中调用full_clean()。
class ConnectedRoute(models.Model):
bus_stop_1 = models.ForeignKey(
BusStop, on_delete=models.CASCADE, related_name='stop1')
bus_stop_2 = models.ForeignKey(
BusStop, on_delete=models.CASCADE, related_name='stop2')
distance = models.FloatField(blank=True, null=True)
time = models.TimeField(blank=True, null=True)
def clean(self):
if self.bus_stop_1 == self.bus_stop_2:
raise ValidationError('Both stop cannot be the same')
count_stop1 = ConnectedRoute.objects.filter(
bus_stop_1=self.bus_stop_1).count()
count_stop2 = ConnectedRoute.objects.filter(
bus_stop_2=self.bus_stop_2).count()
if count_stop1 + count_stop2 > 4:
raise ValidationError('Only 4 connections allowed.')
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)}