我正在使用 django-rest-swagger 来记录和测试 API,到目前为止它运行良好,但出现了以下错误:
/docs/api-docs/app 的属性错误 “PeriodSerializer”对象没有属性“get_fields”
'PeriodSerializer'继承自serializers.BaseSerializer:
class PeriodSerializer(serializers.BaseSerializer):
def to_representation(self, instance):
return {
'lower': instance.lower,
'upper': instance.upper
}
def to_internal_value(self, data):
data = json.loads(data)
date_lower = self.date_from_str(data["lower"])
date_upper = self.date_from_str(data["upper"])
# some code omitted for brevity
return DateTimeTZRange(lower=date_lower, upper=date_upper)
@staticmethod
def date_from_str(datestr):
# code omitted for brevity
代码本身工作正常,只是 django-rest-swagger 似乎有问题。我正在使用:
- python 3.4.0
- Django 1.8.2
- DRF 3.1.3
- django-rest-swagger 0.3.2
如有任何帮助,我们将不胜感激。
最佳答案
Django Rest Framework 的 BaseSerializer
没有 get_fields
函数。您可以在 source 中看到这一点.
简短回答:使用Serializer
,而不是BaseSerializer
。您的代码将以同样的方式工作,您不必为此担心。如果出于某种原因你需要同时使用 BaseSerializer
和 django-rest-swagger
,你必须自己实现 get_fields
。
如果您在更高级别的序列化程序(如 Serializer
)中查看 get_fields 的实现,您会看到 get_fields 的定义如下:
def get_fields(self):
"""
Returns a dictionary of {field_name: field_instance}.
"""
# Every new serializer is created with a clone of the field instances.
# This allows users to dynamically modify the fields on a serializer
# instance without affecting every other serializer class.
return copy.deepcopy(self._declared_fields)
使用 BaseSerializer,您也无法访问 self._declared_fields。您可以在上面的链接源中看到它是如何工作的,但它的要点是它返回 Field 类型的属性字典。
Any instances of
Field
included as attributes on either the class or on any of its superclasses will be include in the_declared_fields
dictionary.
我希望这有助于回答您的问题!
关于python - Swagger 不使用 Django BaseSerializer 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30880375/