gpt4 book ai didi

Django REST Framework 自定义字段验证

转载 作者:行者123 更新时间:2023-11-28 19:33:36 34 4
gpt4 key购买 nike

我正在尝试为模型创建自定义验证,以检查其 start_date 是否在其 end_date 之前,事实证明这几乎是不可能的。

我尝试过的东西:

  • 内置的 Django 验证器:没有检查这个

  • 像这样写我自己的:

    def validate_date(self):
    if self.start_date < self.end_date:
    raise serializers.ValidationError("End date must be after start date.")

我已经添加到 Serializer 类(然后是模型)的那段代码,但它似乎没有在任何一个位置被调用。

我还找到了this一些可能有用的代码,但我不知道如何将其集成到我的方法中 - 似乎可以验证一个模型属性,但我需要在两个属性之间进行检查。

我的模型:

class MyModel(models.Model):

created = models.DateTimeField(auto_now_add=True)
relation_model = models.ForeignKey(RelationModel, related_name="mymodels")
priority = models.IntegerField(
validators = [validators.MinValueValidator(0), validators.MaxValueValidator(100)])
start_date = models.DateField()
end_date = models.DateField()

@property
def is_active(self):
today = datetime.date.today()
return (today >= self.start_date) and (today <= self.end_date)

def __unicode__(self):
...

class Meta:
unique_together = ('relation_model', 'priority', 'start_date', 'end_date')

仅供引用,所有其他验证都有效!

我的序列化器:

class MyModelSerializer(serializers.ModelSerializer):

relation_model = RelationModelSerializer
is_active = serializers.Field(source='is_active')

def validate_date(self):
if self.start_date > self.end_date:
raise serializers.ValidationError("End date must be after start date.")

class Meta:
model = MyModel
fields = (
'id', 'relation_model', 'priority', 'start_date', 'end_date', 'is_active'
)

我的看法:

class MyModelList(generics.ListCreateAPIView):
permission_classes = (IsAdminUser,)
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
ordering = ('priority')

最佳答案

您应该使用对象范围的验证 (validate()),因为 validate_date 永远不会被调用,因为 date 不是序列化器。 From the documentation :

class MySerializer(serializers.ModelSerializer):
def validate(self, data):
"""
Check that the start is before the stop.
"""
if data['start_date'] > data['end_date']:
raise serializers.ValidationError("finish must occur after start")
return data

根据 Michel Sabchuk 的建议,您可以将验证错误添加到 end_date 字段:

class MySerializer(serializers.ModelSerializer):
def validate(self, data):
"""
Check that the start is before the stop.
"""
if data['start_date'] > data['end_date']:
raise serializers.ValidationError({"end_date": "finish must occur after start"})
return data

另一种可能性是创建一个验证器。我根据 UniqueTogetherValidator 的代码创建了一个:

from rest_framework.utils.representation import smart_repr

class DateBeforeValidator:
"""
Validator for checking if a start date is before an end date field.
Implementation based on `UniqueTogetherValidator` of Django Rest Framework.
"""
message = _('{start_date_field} should be before {end_date_field}.')

def __init__(self, start_date_field="start_date", end_date_field="end_date", message=None):
self.start_date_field = start_date_field
self.end_date_field = end_date_field
self.message = message or self.message

def __call__(self, attrs):
if attrs[self.start_date_field] > attrs[self.end_date_field]:
message = self.message.format(
start_date_field=self.start_date_field,
end_date_field=self.end_date_field,
)
# Replace the following line with
# raise serializers.ValidationError(
# {self.end_date_field: message},
# code='date_before',
# )
# if you want to raise the error on the field level
raise serializers.ValidationError(message, code='date_before')

def __repr__(self):
return '<%s(start_date_field=%s, end_date_field=%s)>' % (
self.__class__.__name__,
smart_repr(self.start_date_field),
smart_repr(self.end_date_field)
)


class MySerializer(serializers.ModelSerializer):
class Meta:
# If your start/end date fields have another name give them as kwargs tot the
# validator:
# DateBeforeValidator(
# start_date_field="my_start_date",
# end_date_field="my_end_date",
# )
validators = [DateBeforeValidator()]

在 DRF 3.0 之前,您还可以将它添加到模型的清理函数中,但在 DRF 3.0 中不再调用它。

class MyModel(models.Model):
start_date = models.DateField()
end_date = models.DateField()
def clean(self):
if self.end_date < self.start_date:
raise ValidationError("End date must be after start date.")

关于Django REST Framework 自定义字段验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31278418/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com