Django:如何在发布请求时将数据保存到数据库之前检查数据是否正确?

我希望能够通过将数据发送到我的函数来解析来自我的 django rest api 项目中的 post 请求的数据,如果该数字在将其保存到数据库之前有效,则返回 true 或 false,如果错误发送自定义发送给执行请求的客户端的错误请求消息。


有人告诉我我可以覆盖 create 方法来做到这一点,但我不知道如何去做。


到目前为止,我的代码如下所示:


class Messages(models.Model):

    phone_number = models.CharField(max_length=256, default='')

    message_body = models.CharField(max_length=256, default='')

    created = models.DateTimeField(auto_now_add=True)


    def __str__(self):

        return self.phone_number + ' ' + self.message_body + ' ' + self.created


    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):

        # I assume this is where I would do the check before saving it but not sure how? example would be like:

        # if numberValid(self.phone_number):

        #    then save to the database

        # else:

        #    then send back a bad request?

        super(Messages, self).save(force_update=force_update)

        send_sms(self.phone_number, self.message_body)


    def delete(self, using=None, keep_parents=False):

        super(Messages, self).delete(using=using, keep_parents=keep_parents)

所以基本上只是想知道如何解决这个问题的一些方向。甚至有用的链接将不胜感激。我确实查看了 stackoverflow 但没有成功,也许我不知道如何在搜索时正确表达问题。


交互式爱情
浏览 286回答 3
3回答

料青山看我应如是

您可以使用 DRF Serializer 的验证。例如,创建一个序列化程序,并添加一个验证方法命名validate_<field_name>。然后在那里添加验证代码:import reclass MessagesSerializer(serializers.ModelSerializer):&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model = Messages&nbsp; &nbsp; &nbsp; &nbsp; fields = "__all__"&nbsp; &nbsp; def validate_phone_number(self, value):&nbsp; &nbsp; &nbsp; &nbsp; rule = re.compile(r'(^[+0-9]{1,3})*([0-9]{10,11}$)')&nbsp; &nbsp; &nbsp; &nbsp; if not rule.search(value):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise serializers.ValidationError("Invalid Phone Number")&nbsp; &nbsp; &nbsp; &nbsp; return value并在视图中使用它:class SomeView(APIView):&nbsp; &nbsp; def post(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp;serializer = MessagesSerializer(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data=request.data&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp;if serializer.is_valid():&nbsp; # will call the validate function&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; serializer.save()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Response({'success': True})&nbsp; &nbsp; &nbsp; &nbsp;else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Response(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;serializer.errors,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;status=status.HTTP_400_BAD_REQUEST&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )

牛魔王的故事

查看官方文档了解如何完成此操作:https : //docs.djangoproject.com/en/2.2/ref/models/instances/#django.db.models.Model.clean此方法应用于提供自定义模型验证,并根据需要修改模型上的属性。例如,您可以使用它自动为字段提供值,或者进行需要访问多个字段的验证:def clean(self):&nbsp; &nbsp; # Don't allow draft entries to have a pub_date.&nbsp; &nbsp; if self.status == 'draft' and self.pub_date is not None:&nbsp; &nbsp; &nbsp; &nbsp; raise ValidationError(_('Draft entries may not have a publication date.'))&nbsp; &nbsp; # Set the pub_date for published items if it hasn't been set already.&nbsp; &nbsp; if self.status == 'published' and self.pub_date is None:&nbsp; &nbsp; &nbsp; &nbsp; self.pub_date = datetime.date.today()实现一个clean方法,ValidationError如果它检测到数据有问题,就会引发一个。然后,您可以通过调用在视图中捕获此内容model_obj.full_clean():from django.core.exceptions import NON_FIELD_ERRORS, ValidationErrortry:&nbsp; &nbsp; article.full_clean()except ValidationError as e:&nbsp; &nbsp; non_field_errors = e.message_dict[NON_FIELD_ERRORS]

米脂

您想在保存之前验证字段。有很多技术可以做到这一点。使用序列化程序。如果您使用的是 django rest 框架,那么您可以轻松地使用序列化程序进行验证。&nbsp;https://www.django-rest-framework.org/api-guide/validators/Django 模型验证。这是通过覆盖模型类中的一些可用方法来实现的。&nbsp;https://docs.djangoproject.com/en/2.2/ref/models/instances/#validating-objects对于您的情况,我建议第二种选择。覆盖文档中的方法 clean_fields。然后在保存之前调用该方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python