gpt4 book ai didi

python - 使用 Django Rest Frame 序列化非 django 模型

转载 作者:行者123 更新时间:2023-12-01 09:17:17 26 4
gpt4 key购买 nike

我正在尝试使用 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__)

我的序列化器实现

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

我想要一种序列化 errors 的方法有效负载中的 json 数组。它不绑定(bind)到任何 django 模型。它封装了与其他 django 模型相关的所有错误。这个想法是,如果我能够创建 GameRegistration ,然后我将返回以下有效负载


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

如果出现错误,我将返回有效负载,如下所示:
{
'errors': {
'error_code': 500,
'error_message': 'Server error'
}
}

最佳答案

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

class BaseSerializer(serializers.<b>Serializer</b>, object):
pass

ModelSerializer 的问题是,它期望一个 Meta 类,其中至少有两个字段,其中 fields型号

关于python - 使用 Django Rest Frame 序列化非 django 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com