在DRF modelViewSet上执行创建和更新的自定义函数 [英] Custom function which performs create and update on DRF modelViewSet

查看:920
本文介绍了在DRF modelViewSet上执行创建和更新的自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 modelviewset 中创建一个自定义方法,该方法需要在单个发布请求中执行保存和更新逻辑。

Hi there I want to create a custom method in a modelviewset which needs to perform a save and an update logic in a single post request.

这是我的 breeding.viewsets.py

class BreedingViewSet(viewsets.ModelViewSet):
    queryset = Breeding.objects.all()
    serializer_class = BreedingSerializer




由于上述方法具有较高的抽象水平,并且
实际上是提供或执行自动CRUD功能。

Since the above method has a higher level of abstraction and is actually providing or performing automatic CRUD functions.

现在的问题是,我无法控制多个查询,例如在单个发布请求中保存对象并更新另一个对象。

例如

def save_and_update(self, request):
     // do save an object here.
     // do update an object here.

我们如何实现如此强大的功能?我错过了什么吗?我发现了这个文档但我不知道如何执行给定的指令。

How can we achieve such powerful functionalities? Did i missed something? I found this documentation but i dont know how to implement the given instruction.

更新

这就是我正在寻找的如何创建

但是答案只能保存的多个实例?同一模型的单个发布请求。但是我也希望我们可以在该单个函数中对不同的模型执行查询。

But the answer can only save a multiple instances in a single post request of that same model. But Im hoping also that we can perform queries for a different models in that single function.

推荐答案

从注释中,它看起来您想在创建繁殖模型时更新一些不相关的模型。这应该很容易。

Well, from the comments, it looks like you want to update some unrelated model when you create your breeding model. This should be easy.


class BreedingViewSet(viewsets.ModelViewSet):
    queryset = Breeding.objects.all()
    serializer_class = BreedingSerializer

    def create(self, request):
        # do your thing here
        return super().create(request)

这篇关于在DRF modelViewSet上执行创建和更新的自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆