簡體   English   中英

通過父模型場驗證

[英]Validate through parents model fileds

我有兩個模型:

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的位置字段可以來自或到。 例如,如果我從-倫敦到-紐約,我只能在這兩個地方之間選擇子模型的地方。 如何在序列化器中執行? 謝謝!

要對多個Model字段進行自定義驗證,應使用Model.clean()

https://docs.djangoproject.com/zh_CN/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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM