【问题标题】:DRF: validate a field from another tableDRF:验证另一个表中的字段
【发布时间】:2018-08-30 16:41:47
【问题描述】:

我创建了一个 API 来上传文件。现在我想在用户上传之前添加一些检查。所以在有效载荷中,我要求他的电子邮件和令牌来验证他。

现在电子邮件和令牌在单独的表中。我怎样才能验证它们。我收到类似的错误

TypeError: 'email' is an invalid keyword argument for this function

我的模型文件

class File(models.Model):

    filename = models.FileField(blank=False, null=False,upload_to='files')
    remark = models.CharField(max_length=20)
    timestamp = models.DateTimeField(auto_now_add=True)

我的序列化程序文件

class FileSerializer(serializers.ModelSerializer):

    token = serializers.CharField(label=_("Token"))
    email = serializers.CharField(label=_('email'))

    def validate(self, attrs):
        print("validating params")
        token = attrs.get('token')
        email= attrs.get('email')

        validate(token, email)
        return attrs

    class Meta():
        model = File
        fields = ('filename', 'remark', 'timestamp', 'token', 'email')
        read_only_fields = ('token', 'email')

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    在创建文件(上传)时只需要 emailtoken 并且它们不是模型中的字段,因此您应该将它们设为 write_only 并且您应该覆盖序列化程序中的 create 方法并在保存到模型中之前将它们弹出。

     class FileSerializer(serializers.ModelSerializer):
    
        token = serializers.CharField(label=_("Token"), write_only=True)
        email = serializers.CharField(label=_('router_macid'), write_only=True)
    
        def validate(self, attrs):
            print("validating params")
            token = attrs.get('token')
            email= attrs.get('email')
    
            validate(token, email)
            return attrs
    
        def create(self, validated_data):
            validated_data.pop('email', None)
            validated_data.pop('token', None)
            return super().create(validated_data)
    
    
    
        class Meta():
            model = File
            fields = ('filename', 'remark', 'timestamp', 'token', 'email')
    

    【讨论】:

    • 谢谢,我会试试这个。
    • 很高兴它有帮助。
    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2011-09-20
    • 1970-01-01
    • 2017-01-28
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多