简体   繁体   English

Django 模型视图集。 如何合并两个执行方法/函数?

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

Is there a way to merge perform methods/functions?有没有办法合并执行方法/功能? The view uses ModelViewSet.该视图使用 ModelViewSet。 I have two functions perform_create and perform_update that do the same thing and I wondered could I merge them somehow?我有两个函数perform_createperform_update做同样的事情,我想知道我能以某种方式合并它们吗?

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:perform_create function 也分配为perform_update

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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