简体   繁体   中英

Django ModelViewSet. How to merge two perform methods/functions?

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__'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM