serializers.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from rest_framework import serializers
  2. from bitfield.types import BitHandler
  3. from .models import APIToken
  4. class BitFieldSerializer(serializers.Field):
  5. """
  6. BitField model field serializer
  7. Displays as list of true flag
  8. Semi inspired from django-bitfield bitfield/forms.py
  9. """
  10. def to_internal_value(self, data):
  11. model_field = getattr(self.root.Meta.model, self.source)
  12. result = BitHandler(0, model_field.keys())
  13. for k in data:
  14. try:
  15. setattr(result, str(k), True)
  16. except AttributeError:
  17. raise serializers.ValidationError("Unknown choice: %r" % (k,))
  18. return result
  19. def to_representation(self, value):
  20. return [i[0] for i in value.items() if i[1] is True]
  21. class APITokenAuthScopesSerializer(serializers.ModelSerializer):
  22. scopes = BitFieldSerializer()
  23. class Meta:
  24. model = APIToken
  25. fields = ("scopes",)
  26. class APITokenSerializer(APITokenAuthScopesSerializer):
  27. dateCreated = serializers.DateTimeField(source="created", read_only=True)
  28. scopes = BitFieldSerializer()
  29. class Meta(APITokenAuthScopesSerializer.Meta):
  30. fields = ("scopes", "dateCreated", "label", "token", "id")