Skip to content

Instantly share code, notes, and snippets.

@kerin
Created March 24, 2020 14:50
Show Gist options
  • Save kerin/6ec1ea574e1d020d795c475eb4ca8766 to your computer and use it in GitHub Desktop.
Save kerin/6ec1ea574e1d020d795c475eb4ca8766 to your computer and use it in GitHub Desktop.
class LegalBasisDataWorkspaceSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
"""
Create {consent_type}_consent field for each Consent type.
This flattens consent status in the API response, rather than returning
nested serialized Consent objects
"""
super(LegalBasisDataWorkspaceSerializer, self).__init__(*args, **kwargs)
all_consent_types = list(Consent.objects.all().values_list("name", flat=True))
for consent_type in all_consent_types:
field_name = f"{consent_type}_consent"
method_name = f"get_{field_name}"
def inner(self, obj) -> bool:
return consent_type in obj.consents.all().values_list("name", flat=True)
setattr(self, method_name, types.MethodType(inner, self))
self.fields[f"{consent_type}_consent"] = serializers.SerializerMethodField(
method_name=method_name
)
class Meta:
model = LegalBasis
exclude = ["consents"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment