Django模型验证两个ArrayFields具有相同的长度

时间:2018-01-10 00:46:59

标签: django postgresql django-models

鉴于两个from django.contrib.postgres.fields import ArrayField class MyModel(models.Model): x = ArrayField(models.FloatField()) y = ArrayField(models.FloatField()) ,如何验证两者的长度总是一样的?

ArrayField

我知道您可以将<?php session_start(); require_once "GoogleAPI/vendor/autoload.php"; $gClient = new Google_Client(); $gClient->setClientId("your_client_id_comes_here"); $gClient->setClientSecret("your_client_secret"); $gClient->setApplicationName("CPI Login Tutorial"); $gClient->setRedirectUri("your_authorized_uri.php"); //addScope sets the permissions you'll have in your app, whether it is only for displaying them or to handle as you desire (e.g.: store account's information, such as email givenName and so on, into your own db $gClient->addScope("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.me"); ?> 大小参数具体化为两者,但如果我希望每个记录的大小可变,该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以通过覆盖Model.clean()方法(Docs)来使用Django模型进行自定义验证。

  

此方法应用于提供自定义模型验证,并根据需要修改模型上的属性。

所以你应该写下这样的东西:

class MyModel(models.Model):
    x = ArrayField(models.FloatField())
    y = ArrayField(models.FloatField())

    def clean(self):
        if len(self.x) != len(self.y):
            raise ValidationError("The arrays do not have the same length.")

Model.clean()作为Model.full_clean()验证流程的一部分执行。请注意,它未在Model.save()上执行。如果您想要执行它并在Model.save()方法上验证它们的长度相同,则必须覆盖Model.save()并在其中调用Model.full_clean()