Last active
April 14, 2021 18:02
-
-
Save kaushil24/7e902561df30134d70f915bec75f932d 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
# parent_serializer.py | |
class MetaObj(): | |
pass | |
class ParentSerializer(serializers.ModelSerializer): | |
def __init__(self, *args, **kwargs): | |
meta_obj = MetaObj() | |
meta_obj.model = ParentModel | |
meta_obj.fields = ["field_1", "field_2"] | |
meta_obj.read_only_fields = ["field 3", "field_4"] | |
self.Meta = meta_obj | |
super().__init__(*args, **kwargs) | |
# child_serializer.py | |
class ChildSerializer(ParentSerializer): | |
new_field = serializers.CharField(default="this a new added field coming form child serializer.") | |
# Approach 1: Appending the "new_field" to the existing fields that ParentSerializer has | |
class Meta: | |
parent_serializer = ParentSerializer() | |
existing_fields = parent_serializer.Meta.fields | |
fields = list(parent_serializer.Meta.fields) + ["new_field"] | |
# Approach 2: Appending the "reports" field in the constructor and creating meta within constructor. | |
def __init__(self, *args, **kwargs): | |
parent_serializer = ParentSerializer(*args, **kwargs) | |
self.Meta = parent_serializer.Meta | |
self.Meta.fields = list(parent_serializer.Meta.fields) | |
self.Meta.fields.append("new_field") | |
super().__init__(*args, **kwargs) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment