[Django]-Serializer ForeignKey results in "Expected a dictionary …"

3👍

You can user model_to_dict method as bellow:

from django.forms.models import model_to_dict
model_to_dict(obj)

1👍

You have defined fontId as being a serialized object (FontSerializer). But that serializer in turn is defined as having both an id and a name. Where as your json dictionary is posting only an id. You would have to change that to a dictionary that contains both an id and a name

{
  fontId: {id: "4a14a055-3c8a-43ba-aab3-221b4244ac73",name: "some name" },
  id: "40da7a83-a204-4319-9a04-b0a544bf4440"
  unit: "aaa"
}
👤e4c5

1👍

The reason you are getting this error is that during deserialization process, DRF calls .is_valid(raise_exception=True) before you can call serializer.save(validated_data). And non_field_errors lists any general validation errors during this process. In your GlyphSerializer, your FontSerializer is a nested serializer, which correlates to a Python dictionary. So it will raise an error like you encountered for any non-dictionary data types.

You could create a subclass of GlyphSerializer called GlyphCreateSerializer

class FontSerializer(serializers.ModelSerializer):
    class Meta:
        model = Font
        fields = ('id', 'name')


class GlyphSerializer(serializers.ModelSerializer):
    fontId = FontSerializer(source='font')
    class Meta:
        model = Glyph
        fields = ('id', 'unit', 'fontId' )

class GlyphCreateSerializer(GlyphSerializer):
    fontId = serializers.CharField()

And you can use GlyphCreateSerializer for the POST request on your Viewset.

Leave a comment