24👍
✅
Solution is simple as changing
class GenericCharacterFieldMixin():
to
class GenericCharacterFieldMixin(serializers.Serializer):
37👍
Set SerializerMetaclass
:
from rest_framework import serializers
class GenericCharacterFieldMixin(metaclass=serializers.SerializerMetaclass):
# ...
This is the solution recommended by DRF’s authors.
Solutions suggested in the previous answers are problematic:
- user1376455’s solution hacks DRF into registering the mixin’s fields in
_declared_fields
by declaring them on the child as different fields. This hack might not work in subsequent versions of the framework. - Nikolay Fominyh’s solution changes the mixin to a fully fledged serializer (note that due to this, the name
GenericCharacterFieldMixin
is very unfortunate for a class which is not a mixin, but a serializer!). This is problematic because it takes the fullSerializer
class into the multiple inheritance, see the DRF issue for examples demonstrating why this is a bad idea.
- [Django]-Django-nonrel + Django-registration problem: unexpected keyword argument 'uidb36' when resetting password
- [Django]-Malformed Packet: Django admin nested form can't submit, connection was reset
- [Django]-Ignoring Django Migrations in pyproject.toml file for Black formatter
3👍
i had same issue and my google search brought me here. i managed to solve it.
since you are including attributes and skill fields in serialiser, you need to provide serialisation method for it.
this worked for me
class MageSerializer(GenericCharacterFieldMixin, serializers.ModelSerializer):
player = serializers.ReadOnlyField(source='player.username')
arcana = serializers.SerializerMethodField()
attributes = serializers.PrimaryKeyRelatedField(many=True,
read_only= True)
skills = serializers.PrimaryKeyRelatedField(many=True,
read_only= True)
def get_arcana(self, obj):
if obj:
return {str(arcana): arcana.current_value for arcana in obj.linked_arcana.all()}
class Meta:
model = Mage
fields = ('id', 'player', 'name', 'sub_race', 'faction', 'is_published',
'power_level', 'energy_trait', 'virtue', 'vice', 'morality', 'size',
'arcana', 'attributes', 'skills')
depth = 1
- [Django]-Django Rest Framework model serializer with out unique together validation
- [Django]-Github issues api 401, why? (django)
- [Django]-What does 'many = True' do in Django Rest FrameWork?
Source:stackexchange.com