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.