Reputation: 12341
Given two ArrayField's
, how you can validate the length of both are always the same?
from django.contrib.postgres.fields import ArrayField
class MyModel(models.Model):
x = ArrayField(models.FloatField())
y = ArrayField(models.FloatField())
I know you can specific the ArrayField
size parameter to be the same on both, but what if I want the size to be variable for each record?
Upvotes: 0
Views: 427
Reputation: 11450
You can do custom validation with Django models by overriding the Model.clean()
method (Docs).
This method should be used to provide custom model validation, and to modify attributes on your model if desired.
So you should be able to write something like this:
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()
is executed as part of the Model.full_clean()
validation flow. Notice that it's not executed on Model.save()
. If you would like to execute it and validate that they are the same length on the Model.save()
method, you will have to override Model.save()
and call Model.full_clean()
in it.
Upvotes: 1