社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

Django ModelViewSet。如何合并两个执行方法/功能?

HackerMF • 3 年前 • 1397 次点击  

有没有合并执行方法/函数的方法?该视图使用ModelViewSet。我有两个功能 执行创建 执行更新 它们做了同样的事情,我想知道我能不能合并它们?

身体

{
    "title": "1 Title",
    "description": "1 Description",
    "author": {
        "id": 1
    }
}

看法

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)

串行器

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = '__all__'


class ArticleSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()

    class Meta:
        model = Article
        fields = '__all__'
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130771
 
1397 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    3 年前

分配 perform_create 充当 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