I am trying to write serializers for my models that are inherited from some base classes, but I get an attribute error. I would appreciate any help.
Base class:
class AbstractTranslationModel(models.Model): class Meta: abstract = True language = models.CharField(max_length=2, choices=LANGUAGES)
Subclass:
class SkillTranslation(AbstractTranslationModel): class Meta: unique_together = (('translation_of', 'language'), )
Here is the serializer for this class:
class SkillTrSerializer(serializers.ModelSerializer): class Meta: model = SkillTranslation fields = ('language', 'name', 'description', )
And here is the serializer for the class, which contains the following:
class SkillSerializer(serializers.ModelSerializer): translations = SkillTrSerializer() class Meta: model = Skill fields = ('translations', )
Here is the console output:
>>> 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'.
EDIT: Here is more information.
>>> 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)
Thanks Anton