用Django-Rest-Fram序列化非Django模型

2024-05-23 13:46:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation self.child.to_representation(item) for item in iterable File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp> self.child.to_representation(item) for item in iterable File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 510, in to_representation fields = self._readable_fields File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 376, in _readable_fields field for field in self.fields.values() File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 997, in get_fields serializer_class=self.__class__.__name__ AssertionError: Class ErrorSerializer missing "Meta" attribute

我的模型如下:

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__)

我的序列化程序实现

^{pr2}$

我想要一种在有效负载中序列化errorsjson数组的方法。它不绑定到任何django模型。它封装了与其他django模型相关联的所有错误。其思想是,如果我能够创建GameRegistration,那么我将返回以下有效负载

{ 'game_id': 'ABCDabcd1234', 'created': '<created stamp>' }

如果出现错误,我将按如下方式返回有效载荷: { 'errors': { 'error_code': 500, 'error_message': 'Server error' } }


Tags: toinselfenvgamelibpackagessite