Aaron Lelevier Aaron Lelevier - 4 months ago 19
Python Question

Define an arbitrary Field on a django-rest-framework Serializer that doesn't exist on the Django Model

I'd want to define an arbitrary

Field
on a django-rest-framework
Serializer
that doesn't exist on the Django
Model
.

My code looks like so:

class Person(models.Model):
pass

class PersonSerializer(serializers.ModelSerializer):

foo = serializers.CharField()

class Meta:
model = Person
fields = ('id', 'foo')

class PersonViewSet(viewsets.ModelViewSet):

queryset = Person.objects.all()
serializer_class = PersonSerializer


This code fails with:

AttributeError: Got AttributeError when attempting to get a value for field `key` on serializer `PersonSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Person` instance.
Original exception text was: 'Person' object has no attribute 'key'.


But... If I adjust the
Person
class to this:

class Person(models.Model):

def foo(self):
pass


Then I don't get the error, and I can POST the data.

I don't like the idea of creating a dummy method on the
Person
class to get around this error. Is there a django-rest-framework way to alleviate this error that I missed?

wim wim
Answer

You could do it like this, using a SerializerMethodField:

class PersonSerializer(serializers.ModelSerializer):

    foo = serializers.SerializerMethodField()

    ...

    def get_foo(self, obj):
        return 'the foo'

Then the logic about how to serialize the additional field just lives on the serializer itself, however it does have access to the instance, if required, through obj.