ModelSerializer中的附加信息未使用Model

时间:2013-12-15 13:29:07

标签: django django-rest-framework

我遇到类似这样的问题:Additional (non model) fields in ModelSerializer

我想创建一个带有modelserializer的对象,如下所示:

class CreateUserSerializer(serializers.ModelSerializer):
    user = serializers.CharField(source="username")
    password = serializers.CharField()
    password2 = serializers.WritableField() 
    ...

    class Meta:
         model = User
     fields = ('user', "password", "password2", ...)

显然,我对保存password2不感兴趣,只是出于比较的原因。

理想情况下,这应该可以解决问题,但由于原因,它无法按预期工作:

def restore_object(self, attrs, instance=None):
    tags = attrs.pop('password2', None)
    obj = super(CreateUserSerializer, self).restore_object(attrs, instance)
    obj.tags = tags
    logging.info(u"Object gets restored, field 'password2' gets removed,  list with arguments for object: {0}".format(tags))
    return obj

我得到的错误是:

'User' object has no attribute 'password2'
 ...
 /home/jan/projekte/alarmapp/eclipse_workspace/AlarmServer/AlarmApp/src/external/rest_framework/fields.py in get_component

55. val = getattr(obj, attr_name)

任何想法为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

似乎this small Gist应该会有所帮助:

from django.contrib.auth.models import User
from rest_framework import serializers

class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField()

    def validate_password2(self, attrs, source):
        password2 = attrs.pop(source)
        if attrs['password'] != password2:
            raise serializers.ValidationError('password mismatch')
        return attrs

    def to_native(self, obj):
        self.fields.pop('password2')
        return super(CreateUserSerializer, self).to_native(obj)

    class Meta:
        model = User