【发布时间】:2019-10-18 05:11:01
【问题描述】:
我已经为模型编写了一个自定义保存方法,以防止保存无效数据,但是当我想通过管理员更新对象时(只是为了更改一些属性),我得到了一个断言错误
我的模特:
class Segment(CoreModel):
departure = models.ForeignKey(Place, on_delete=models.CASCADE, limit_choices_to=limit_choices_segment,
related_name='departures')
destination = models.ForeignKey(Place, on_delete=models.CASCADE, limit_choices_to=limit_choices_segment,
related_name='arrivals')
distance = models.FloatField(help_text='Distance between places in "km"!', null=True, blank=True,
validators=[property_positive_value])
duration = models.FloatField(help_text='Transfer duration (hours)', null=True, blank=True,
validators=[property_positive_value])
cost = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True,
help_text='Price for a transfer! Currency: "UAH"!',
validators=[property_positive_value])
route = models.ForeignKey(Route, on_delete=models.CASCADE, related_name='segments')
def __str__(self):
return '{}-{}'.format(self.departure, self.destination)
def save(self, *args, **kwargs):
assert self.departure.role not in (Place.DISTRICT, Place.REGION), (
"Departure couldn't be Region or District")
assert self.destination.role not in (Place.DISTRICT, Place.REGION), (
"Destination couldn't be Region orDistrict")
assert self.destination != self.departure, "Departure couldn't be equal to Destination"
assert self.route.segment_validate(departure=self.departure, destination=self.destination), (
'Impossible to add the segment, please check the route!')
if self.distance is not None:
assert self.distance > 0, "Distance couldn't be less or equal to '0'!"
if self.duration is not None:
assert self.duration > 0, "Duration couldn't be less or equal to '0'!"
if self.cost is not None:
assert self.cost > 0, "Cost couldn't be less or equal to '0'!"
super(Segment, self).save(*args, **kwargs)
验证方法:
def segment_validate(self, departure, destination):
segments = self.segments.all()
if segments:
for segmnet in segments:
same_departure = segmnet.departure == departure
same_destination = segmnet.destination == destination
if ((same_departure and same_destination) or
same_departure or same_destination):
return False
if segments.latest('created').destination != departure:
return False
return True
错误在这里:
assert self.route.segment_validate(departure=self.departure, destination=self.destination), (
'Impossible to add the segment, please check the route!')
但我没有更改 departure 和 destination
你能帮我避免这个错误吗?
【问题讨论】:
-
好吧,既然您已经添加了该细分,那么该细分现在与自身发生冲突!
-
@WillemVanOnsem,您知道如何解决吗?因为我不能跳过导致错误的验证方法?
-
顺便问一下
self.segments在这里做什么?看起来这是Route模型的验证器? -
@WillemVanOnsem,是的,它来自
Route模型的验证器,它检查是否可以向路线添加新段 -
您在保存中的断言将导致用户出现 500 个错误(至少如果它们发生在管理员那里),最好在您的表单代码中进行验证,并编写一个
Model.clean(..)引发的方法ValidationErrors处理您在保存中所做的验证...(文档:docs.djangoproject.com/en/dev/ref/models/instances/… 相关 SO stackoverflow.com/questions/8771029/…)
标签: python django django-models