I have two serializers which use a same function. I want to define it as a static method and reuse it.
Serializer for Article
class ArticleDetailSerializer(ModelSerializer):
liked = SerializerMethodField()
class Meta:
model = Article
fields = [
'id',
'self_liked',
'title'
]
def get_liked(self, obj):
request = self.context.get('request')
self_like_obj = Reaction.objects.filter(user=request.user.id, content_type=ContentType.objects.get(model='article'), object_id=obj.id)
if self_like_obj.exists():
self_like = Reaction.objects.get(user=request.user.id, content_type=ContentType.objects.get(model='article'), object_id=obj.id).react_type
else:
self_like = False
return self_like
Serializer for comment
class CommentSerializer(ModelSerializer):
liked = SerializerMethodField()
class Meta:
model = Comment
fields = [
'id',
'self_liked',
'content'
]
def get_liked(self, obj):
request = self.context.get('request')
self_like_obj = Reaction.objects.filter(user=request.user.id, content_type=ContentType.objects.get(model='comment'), object_id=obj.id)
if self_like_obj.exists():
self_like = Reaction.objects.get(user=request.user.id, content_type=ContentType.objects.get(model='comment'), object_id=obj.id).react_type
else:
self_like = False
return self_like
As you see, two serializer use a general function: get_liked
How can I define it as a static methods for reuse?