Почему возникает исключение, когда я открываю validated_data в DRF?
Я выполняю создание, используя DRF's ModelSerializer
. В текущей модели есть внешний ключ под названием description_type
. Поэтому, когда я получаю запрос, я получаю его как строку в поле с именем description_type_code
, раскрываю description_type_code
в validated_data
метода create()
сериализатора и использую этот description_type_code
для получения соответствующей description_type
модели. Однако выполнение этой задачи приводит к следующим ошибкам.
Got AttributeError when attempting to get a value for field `description_type_code` on serializer `PostSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'description_type_code'.
Что не так с моим кодом? Вот мой код.
models.py
class Post(models.Model):
...
description_type = models.ForeignKey(DescriptionType, models.DO_NOTHING, db_column='description_type')
...
serializers.py
class PostSerializer(serializers.ModelSerializer):
description_type_code = serializers.CharField()
class Meta:
model = Post
fields = ('title', 'description', 'description_type_code')
def create(self, validated_data):
description_type_code = validated_data.pop('description_type_code')
description_type = DescriptionType.objects.get(name=description_type_code)
post = Post.objects.create(**validated_data, description_type=description_type)
return post