我有两个模型:
class Foo(models.Model):
from = models.ForeignKey(Place)
to = models.ForeignKey(Place)
class Bar(models.Model):
foo = models.ForeignKey(Foo)
place = models.ForeignKey(Place)
我需要验证Bar的位置字段可以来自或到达。例如,如果我从-伦敦到-纽约,我只能在这两个地方之间选择子模型的地方。如何在序列化器中执行?谢谢!
答案 0 :(得分:2)
要对多个“模型”字段进行自定义验证,应使用Model.clean()
https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean
class Bar(models.Model):
foo = models.ForeignKey(Foo)
place = models.ForeignKey(Place)
def clean(self):
# Your check here
if self.place: #between self.foo.from and self.foo.to
#Your code here
pass
else:
raise ValidationError("Place isn't between frow and to")