Created
March 24, 2020 14:50
-
-
Save kerin/6ec1ea574e1d020d795c475eb4ca8766 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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