Skip to content

Commit

Permalink
feat(api): return (enum) choices labels
Browse files Browse the repository at this point in the history
For multiple-choice fields implemented with
django-multiselectfield and TextChoices, return
the choices' (German language) labels rather than
their values.
  • Loading branch information
koeaw committed May 28, 2024
1 parent 7a7c880 commit 6f137f9
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions apis_ontology/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,22 @@
from apis_ontology.models import Expression, Work, WorkType


def get_choices_labels(values: list, text_choices):
"""
Return labels for enumeration type TextChoices.
:param values: an array of (valid) TextChoices values
:param text_choices: the TextChoices class against which to match the values
:return: a list of labels
"""
labels = []

for v in values:
labels.append(text_choices(v).label)

return labels


class WorkTypeDataSerializer(serializers.ModelSerializer):
class Meta:
model = WorkType
Expand All @@ -24,6 +40,8 @@ class ExpressionDataSerializer(serializers.ModelSerializer):
place_of_publication = serializers.ListField(
child=serializers.CharField(allow_blank=True), required=False, allow_empty=True
)
edition_type = serializers.SerializerMethodField()
language = serializers.SerializerMethodField()

class Meta:
model = Expression
Expand All @@ -38,6 +56,16 @@ class Meta:
"place_of_publication",
]

def get_edition_type(self, obj):
edition_type_str = obj.get("edition_type", None)
edition_types = list(filter(None, edition_type_str.split(",")))
return get_choices_labels(edition_types, Expression.EditionTypes)

def get_language(self, obj):
language_str = obj.get("language", None)
languages = list(filter(None, language_str.split(",")))
return get_choices_labels(languages, Expression.Languages_ISO_639_3)


class WorkPreviewSerializer(serializers.ModelSerializer):
expression_data = ExpressionDataSerializer(required=False, many=True)
Expand Down

0 comments on commit 6f137f9

Please sign in to comment.