4
我想爲我的模型編寫序列化程序,它們是從一些基類繼承的,但是我得到了屬性錯誤。我將不勝感激任何幫助。屬性錯誤Django REST序列化
基類:
class AbstractTranslationModel(models.Model):
class Meta:
abstract = True
language = models.CharField(max_length=2, choices=LANGUAGES)
# Translatable fields
name = models.CharField(max_length=22)
description = models.TextField(default='')
def __str__(self):
return self.name + ' ' + str(self.language)
子類:
class SkillTranslation(AbstractTranslationModel):
class Meta:
unique_together = (('translation_of', 'language'),)
# Foreign keys
translation_of = models.ForeignKey(Skill, related_name='translations',
related_query_name='translation')
下面是這個類串行:
class SkillTrSerializer(serializers.ModelSerializer):
class Meta:
model = SkillTranslation
fields = ('language', 'name', 'description',)
這裏是一類序列化,包含的:
class SkillSerializer(serializers.ModelSerializer):
translations = SkillTrSerializer()
class Meta:
model = Skill
fields = ('translations',)
這裏是控制檯輸出:
>>> from skills.models import *
>>> from api.serializers import *
>>> skill = Skill.objects.all().first()
>>> skill.translations.all()
[<SkillTranslation: English skill EN>, <SkillTranslation: Рашн RU>]
>>> skill.translations.all().first()
<SkillTranslation: English skill EN>
>>> skill.translations.all().first().language
'EN'
>>> s = SkillSerializer(instance=skill)
>>> s.data
AttributeError: Got AttributeError when attempting to get a value for field `language` on serializer `SkillTrSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance.
Original exception text was: 'RelatedManager' object has no attribute 'language'.
編輯:這裏是附加信息
>>> s
SkillSerializer(instance=<Skill: English skill>):
translations = SkillTrSerializer():
id = IntegerField(label='ID', read_only=True)
language = ChoiceField(choices=(('EN', 'English'), ('RU', 'Russian'), ('UA', 'Ukrainian')), required=True)
name = CharField(max_length=22)
description = CharField(required=False, style={'base_template': 'textarea.html'})
translation_of = PrimaryKeyRelatedField(queryset=Skill.objects.all(), required=True)
謝謝,安東
之前,你在哪裏時,我花了3個小:)我感謝上帝,你的回答在這裏。我完全不知道! –
很高興能夠幫助! – miki725