5

I have a model that contains a BitField. When trying to serialize an object using Django Rest Framework, the following error is returned:

{"flags": ["Enter a whole number."]}

(flags is a BitField)

How can I serialize a BitField using Django Rest Framework?

3 Answers 3

4

looks like the form of Tzach's answer in rest-framework 3.1 is now

class BitFieldSerializer(serializers.Field):

     def to_internal_value(self, obj):
         return int(obj)

e.g. per http://www.django-rest-framework.org/api-guide/fields/#custom-fields

"Note that the WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input."

Sign up to request clarification or add additional context in comments.

Comments

3

Found the answer. I needed to create a custom serializer for the BitField:

class BitFieldSerializer(serializers.WritableField):        
    def to_native(self, obj):
        return int(obj)

And use it in the model serializer:

class MyModelSerializer(serializers.ModelSerializer):
    flags = BitFieldSerializer()

Comments

3

Here's another option if you want to read and write the flags in a list.

class BitFieldSerializer(serializers.Field):
    def to_internal_value(self, data):
        model_field = getattr(self.root.Meta.model, self.source)
        result = BitHandler(0, model_field.keys())
        for k in data:
            try:
                setattr(result, str(k), True)
            except AttributeError:
                raise serializers.ValidationError("Unknown choice: %r" % (k,))
        return result

    def to_representation(self, value):
        return [i[0] for i in value.items() if i[1] is True]

Example return: ['flag1', 'flag4']

This assumes you are using a ModelSerializer. The way I get the model field's keys (it's flags) seems a little sketchy if anyone knows a better way please comment.

1 Comment

thanks a lot! This makes it more feasible because with django-bitfield, we don't get the right bit-wise values as a flag. It makes it very hard for clients to make changes to the field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.