[Django]-Mixin common fields between serializers in Django Rest Framework

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:

  1. 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.
  2. 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 full Serializer class into the multiple inheritance, see the DRF issue for examples demonstrating why this is a bad idea.
👤tbitai

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

Leave a comment