Is there a way to merge perform methods/functions? The view uses ModelViewSet. I have two functions perform_create and perform_update that do the same thing and I wondered could I merge them somehow?
Body
{
"title": "1 Title",
"description": "1 Description",
"author": {
"id": 1
}
}
View
class ArticleView(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
def perform_create(self, serializer):
author = get_object_or_404(Author, id=self.request.data['author']['id'])
return serializer.save(author=author)
def perform_update(self, serializer):
author = get_object_or_404(Author, id=self.request.data['author']['id'])
return serializer.save(author=author)
Serializers
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = '__all__'
class ArticleSerializer(serializers.ModelSerializer):
author = AuthorSerializer()
class Meta:
model = Article
fields = '__all__'
CodePudding user response:
Assign the perform_create
function as perform_update
as well:
class ArticleView(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
def perform_create(self, serializer):
author = get_object_or_404(Author, id=self.request.data['author']['id'])
return serializer.save(author=author)
perform_update = perform_create