Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用django Rest框架序列化非django模型_Python_Django_Serialization_Django Rest Framework - Fatal编程技术网

Python 使用django Rest框架序列化非django模型

Python 使用django Rest框架序列化非django模型,python,django,serialization,django-rest-framework,Python,Django,Serialization,Django Rest Framework,我试图用DRF构建一个django模型,该模型在创建后发送一个对象状态负载,或者发送一个错误负载。当我尝试执行类似操作时,会收到以下错误消息: 文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest\u framework/serializers.py”,第527行,以to\u表示 ret[field.field\u name]=field.to\u表示(属性) 文件“/Users/user/proje

我试图用DRF构建一个django模型,该模型在创建后发送一个对象状态负载,或者发送一个错误负载。当我尝试执行类似操作时,会收到以下错误消息:


文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest\u framework/serializers.py”,第527行,以to\u表示
ret[field.field\u name]=field.to\u表示(属性)
文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest\u framework/serializers.py”,第683行,以to\u表示
iterable中项的self.child.to_表示(项)
文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest_framework/serializers.py”,第683行,在
iterable中项的self.child.to_表示(项)
文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest\u framework/serializers.py”,第510行,以to\u表示
字段=自可读字段
文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/django/utils/functional.py”,第36行,在__
res=instance.\uuuu dict\uuuu[self.name]=self.func(实例)
文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest\u framework/serializers.py”,第376行,在可读字段中
self.fields.values()中字段对应的字段
文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest_framework/serializers.py”,第363行,在字段中
对于键,self.get_字段()中的值。项()
文件“/Users/user/projects/bowling game/env/lib/python3.6/site packages/rest\u framework/serializers.py”,第997行,在get\u字段中
序列化程序\u class=self.\u类\u.\u名称__
AssertionError:Class ErrorSerializer缺少“Meta”属性

我的模型如下:

class BaseModel(models.Model, object):
    # Encapsulates all error objects.
    errors= []

    def add_error(self, error_object):
        """Appends the error to the list of errors."""
        self.errors.append(error_object)

    class Meta:
        abstract = True
        app_label = 'game'


class GameRegistration(BaseModel):
    """Instance of this class represents the user playing the bowling game."""

    game_id = models.CharField(max_length=32,
        help_text='Unique bowling game id', primary_key=True,
        default=functools.partial(random_string, char_length=16))
    #  I will set the request.user to set the details later on, but not now.
    user_name = models.CharField(help_text='unique username', default='test', max_length=32)
    created_timestamp = models.DateTimeField(default=datetime.datetime.now)

    class Meta:
        indexes = [
            models.Index(fields=['game_id'])
        ]


class Error(object):
    """
    An instance of this class encapsulates the error code and the message to be
    returned.
    """
    def __init__(self, error_code, error_message):
        self.error_code = error_code
        self.error_message = error_message

    def __repr__(self):
        return '{}:{}'.format(self.__class__.__name__, self.__dict__)
我的序列化程序实现

class BaseSerializer(serializers.ModelSerializer, object):
    pass

class ErrorSerializer(BaseSerializer):
    """Representation of any error resulting in any of the operation."""
    error_code = serializers.IntegerField()
    error_message = serializers.CharField(max_length=200)

    class Meta:
        ordering=('error_code',)

class GameRegistrationSerializer(BaseSerializer):
    """Serializer representation of game instance."""
    game_id = serializers.PrimaryKeyRelatedField(read_only=True)


    def to_representation(self, instance):
        return {
            'game_id': str(instance.game_id),
            'created': instance.created_timestamp
        }

    class Meta:
        model = models.GameRegistration
        fields = ('game_id', 'created')
        read_only_fields = ('game_id', 'created')
我想要一种在有效负载内序列化
错误
json数组的方法。它不绑定到任何django模型。它封装了与其他django模型相关的所有错误。这个想法是,如果我能够创建
游戏注册
,那么我将返回以下有效负载


{
“游戏id”:“ABCD1234”,
“已创建”:”
}

如果出现错误,我将按如下方式返回有效负载:

{
“错误”:{
“错误代码”:500,
“错误消息”:“服务器错误”
}
}

Serializer
类继承
BaseSerializer
,而不是从
ModelSerializer
继承。因此,
BaseSerializer
将类似于

class BaseSerializer(serializers.Serializer, object):
    pass
class BaseSerializer(serializers.Serializer,对象):
通过

ModelSerializer
的问题是,它期望一个
Meta
类至少包含两个
字段,这两个字段分别是
字段和
模型

。Thanks@JPG让你知道为什么需要这样做。在所有其他模块中
类页面序列化器(serializers.ModelSerializer):
工作