Will & Skill Developers

Will & Skill Developers

Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Webdeveloper @ Will & Skill


Django Rest Framework, Many-To-Many and Multipart

Mohammed HammoudMohammed Hammoud

If you are using Django, you have or will probably create a model that includes both a ManyToManyField and a File/ImageField. And if you're using Django Rest Framework and want to created a new object with both a file and m2m values you may encounter the following error:

questions: ["Incorrect type. Expected pk value, received unicode.”]

The problem is that Django Rest Framework doesn't encode [] in multipart. Below you can see how I solved the problem.

from rest_framework import serializers

class MultipartM2MField(serializers.Field):
    def to_representation(self, obj):
        return obj.values_list('id', flat=True).order_by('id')

    def to_internal_value(self, data):
        return data.split(',') if data else None
class MyModelSerializer(serializers.ModelSerializer):

    questions = MultipartM2MField()

Webdeveloper @ Will & Skill