热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在DRF中验证更新字段?-HowtovalidateafieldonupdateinDRF?

Ihaveaserializerforamodelwithaforeignkey.Therequirementisthatoncreate,foreignkeyc

I have a serializer for a model with a foreign key. The requirement is that on create, foreign key can be set to any existing object from the related model, but on update the related object cannot be changed. I can check this in the custom update(), but it would be more elegant to use serializer validation to check for this? But I am not sure how. Example code:

我有一个带有外键的模型的序列化器。需求是在创建时,可以将外键设置为与相关模型中的任何现有对象,但是更新相关对象时不能更改。我可以在custom update()中检查这个,但是使用serializer验证来检查这个是否更好?但我不知道该怎么做。示例代码:

class Person(models.Model):
    name = models.CharField(max_length=256)
    spouse = models.ForeignKey(Person)

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person

    # this is how I know how to do this
    def create(self, validated_data):
        try:
            spouse = Person.objects.get(pk=int(validated_data.pop('spouse')))
        except Person.DoesNotExist:
            raise ValidationError('Imaginary spouses not allowed!')
        return Person.objects.create(spouse=spouse, **validation_data)

    def update(self, person, validated_data):
        if person.spouse.pk != int(validated_data['spouse']):
            raise ValidationError('Till death do us part!')
        person.name = validation_data.get('name', person.name)
        person.save()
        return person

   # the way I want to do this
   def validate_spouse(self, value):
       # do validation magic

1 个解决方案

#1


9  

You can definitely do this using the validation on a field. The way you'd check if it's an update vs. creation is checking for self.instance in the validation function. There's a bit mentioned about it in the serializer documentation.

您肯定可以使用字段上的验证来实现这一点。检查它是更新还是创建的方法是检查self。验证函数中的实例。在serializer文档中有一点提到过。

self.instance will hold the existing object and it's values, so you can then use it to compare against.

自我。实例将保存现有对象及其值,因此您可以使用它进行比较。

I believe this should work for your purposes:

我认为这应该为你的目的而工作:

def validate_spouse(self, value):
    if self.instance and value != self.instance.spouse:
        raise serializers.ValidationError("Till death do us part!")
    return value

Another way to do this is to override if the field is read_only if you're updating. This can be done in the __init__ of the serializer. Similar to the validator, you'd simply look for an instance and if there's data:

另一种方法是重写字段是否为read_only(仅在更新时)。这可以在序列化器的__init__中完成。类似于验证器,您只需查找一个实例,如果有数据:

def __init__(self, *args, **kwargs):
    # Check if we're updating.
    updating = "instance" in kwargs and "data" in kwargs

    # Make sure the original initialization is done first.
    super().__init__(*args, **kwargs)

    # If we're updating, make the spouse field read only.
    if updating:
        self.fields['spouse'].read_Only= True

推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • python3 logging
    python3logginghttps:docs.python.org3.5librarylogging.html,先3.5是因为我当前的python版本是3.5之所 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 本文介绍了PE文件结构中的导出表的解析方法,包括获取区段头表、遍历查找所在的区段等步骤。通过该方法可以准确地解析PE文件中的导出表信息。 ... [详细]
  • Request对象和Response对象request:(请求)当一个页面被请求时,Django就会创建一个包含本次请求原信息的HttpRequest对象。Djang ... [详细]
  • 用Python手把手教你搭建一个web框架-flask微框架!
    在之前的文章当中,小编已经教过大家怎么搭建一个Django框架,今天我们来探索另外的一种框架的搭建,这个框架就是web框架-flask微框架啦!首先我们带着以下的几个问题来阅读本文:1、flask ... [详细]
  • 丛api的python的简单介绍
    本文目录一览:1、如何使用python利用api获取天气预报 ... [详细]
  • 前言无论使用哪种语言,我们都需要关注性能优化,提高执行效率。选择脚本语言需要持久的速度。在某种程度上,这句话说明了Python作为一种脚 ... [详细]
  • 代码如下:#coding:utf-8importosimportsysdefcut_and_paste_file(source,destination):”’sourc ... [详细]
  • 申明下哈本篇文章不是自己写的根据网上的文章再加上自己的加加点点反正大部分都是网站的智慧哈!!!1、线程基本概念1.1线程是什么࿱ ... [详细]
  • 在Python编程教程的这一部分中,我们通常讨论Python编程语言。我们展示了如何执行我们的第一 ... [详细]
  • Commit1ced2a7433ea8937a1b260ea65d708f32ca7c95eintroduceda+Clonetraitboundtom ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
author-avatar
手机用户2502862793
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有