Почему Django показывает объект без атрибута?
Надеюсь у вас все хорошо, я новичок в django и python, столкнулся с ошибкой во время практики, которая находится на REST API FRAMEWORK DictField. Я взял пример на DictField. Я разместил код ниже, пожалуйста, посмотрите. не стесняйтесь спрашивать, если у вас есть какие-либо вопросы. пожалуйста, решите эту проблему. Большое спасибо за помощь.
app1/serializers.py
from rest_framework import serializers
class Geeks(object):
def __init__(self, dictionary):
self.dict = dictionary
class GeeksSerializer(serializers.Serializer):
dictionary = serializers.DictField()
child = serializers.CharField()
python manage.py shell
>>> demo = {}
>>> demo['name'] = "Naveen"
>>> demo['age'] = 21
>>> obj = Geeks(demo)
>>> serializer = GeeksSerializer(obj)
>>> serializer.data
Error:
Traceback (most recent call last):
File "rest_framework\fields.py", line 457, in get_attribute
return get_attribute(instance, self.source_attrs)
File "rest_framework\fields.py", line 97, in get_attribute
instance = getattr(instance, attr)
AttributeError: 'Geeks' object has no attribute 'dictionary'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "rest_framework\serializers.py", line 555, in data
ret = super().data
File "rest_framework\serializers.py", line 253, in data
self._data = self.to_representation(self.instance)
File "rest_framework\serializers.py", line 509, in to_representation
attribute = field.get_attribute(instance)
File "rest_framework\fields.py", line 490, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `dictionary` on serializer `GeeksSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Geeks` instance.
Original exception text was: 'Geeks' object has no attribute 'dictionary'.
Ваш объект Geeks
имеет атрибут dict
, а не атрибут dictionary
, поэтому
У объекта 'Geeks' нет атрибута 'dictionary'.
имеет полный смысл.
Если вы хотите, чтобы поле сериализатора dictionary
читалось из dict
, установите атрибут source
на поле.
dictionary = serializers.DictField(source="dict")
Сериализатор не подходит для формы данных, вы можете исправить это следующим образом
class Geeks(object):
def __init__(self, dictionary):
self.dictionary = dictionary
class GeeksSerializer(serializers.Serializer):
dictionary = serializers.DictField()
child = serializers.CharField(required=False)