Reputation: 720
I have a serializer with two fields as below:
first_installations_date = serializers.SerializerMethodField()
sec_installations_date = serializers.SerializerMethodField()
def get_first_installation_date(self, obj):
return self._extract_date(obj, key="first")
def get_first_installation_date(self, obj):
return self._extract_date(obj, key="sec")
the method for both are the same, with a bit different. Now for refactoring the code, I want to know, is that possible two have a method like:
first_installations_date = serializers.SerializerMethodField(source="get_installation_date", key="first")
sec_installations_date = serializers.SerializerMethodField(source="get_installation_date", key="sec")
def get_installation_date(self, obj, key):
return self._extract_date(obj, key)
Upvotes: 0
Views: 132
Reputation: 3091
No, it is not possible in the way you want unless you create your custom field.
But what about this ? if you really need to "refactor" like that
first_installations_date = serializers.SerializerMethodField()
sec_installations_date = serializers.SerializerMethodField()
def _get_installation_date(self, obj, key):
return self._extract_date(obj, key)
def get_first_installations_date(self, obj):
return self._get_installation_date(obj,key="first")
def get_sec_installations_date(self, obj):
return self._get_installation_date(obj, key="sec")
Upvotes: 1