Reputation: 16808
I have a model without field 'test'. I'm assigning this field in runtime:
ability = Ability.objects.first()
ability.test = 'TEST!!'
I also have the serilizer:
class AbilitySerializer(serializers.ModelSerializer):
class Meta:
model = Ability
fields = ('name', 'test',)
And when I use it:
return Response(AbilitySerializer(ability).data)
I'm getting error:
Field Field name `test` is not valid for model `Ability`.
EDIT: I'm still facing this issue when I'm passing array of objects to serializer (with many=True). It's OK when I pass single instance.
Why and how to fix it?
Upvotes: 0
Views: 2373
Reputation: 4151
As Ajay Gupta indicated, non-model fields/methods/properties must be explicitly declared:
class AbilitySerializer(serializers.ModelSerializer):
# read_only since test is not a model field
test = serializers.CharField(read_only=True)
class Meta:
model = Ability
fields = ('name', 'test',)
Additionally, if you do not always provide test
, consider:
test = serializers.CharField(required=False, read_only=True)
Upvotes: 2