django
有以下模型。该模型创建了一个名为metric_vals
的数组字段,但它允许数组为空数组。有没有办法确保数组始终是非空数组?
from django.db import models
import uuid
from django.contrib.postgres.fields import ArrayField
class SampleModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
metric_vals = ArrayField(models.FloatField(null=False), null=False, default=list)
您可以使用validators
kwarg:
from django.contrib.postgres.validators import ArrayMaxLengthValidator, ArrayMinLengthValidator
def get_default_list():
return [float(1), float(2)]
class SampleModel(models.Model):
metric_vals = ArrayField(
models.FloatField(null=False),
null=False,
# ensure the default passes the validation
default=get_default_list,
# like this
validators=[
ArrayMinLengthValidator(2),
ArrayMaxLengthValidator(10),
]
)
相关:
- https://docs.djangoproject.com/en/4.1/ref/validators/
类似这样的东西:
from django.core.exceptions import ValidationError
class SampleModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
metric_vals = ArrayField(models.FloatField(null=False), null=False, default=list)
def save(self, *args, **kwargs):
if self.metric_vals == []:
raise ValidationError('Empty list not allowed')
super().save(*args, **kwargs)