【问题标题】:How to add two different models in perform_create in REST framework?如何在 REST framework 的 perform_create 中添加两个不同的模型?
【发布时间】:2016-03-25 21:31:52
【问题描述】:

我想通过一个请求一起创建两个模型。这可以在一个perform_create 中完成还是有办法?

型号:

class Foo(models.Model):
   name = models.CharField() 

class Bar(models.Model):
   foo = models.ForeignKey('foo)

观看次数:

class FooViewSet(
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    mixins.CreateModelMixin,
    viewsets.GenericViewSet
):

serializer_class = FooSerializer

def perform_create(self, serializer):
     #???

我希望每次创建 Foo 时都创建 Bar

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    根据您想要做什么,可以在FooSerializer 中使用writeable nested Serializer 进行定义。

    但是,如果您总是“希望每次创建 Foo 时都创建 Bar”,那么我将通过 catching the Foo Model's post_save signal 执行此操作并创建所需的 Bar。例如,即使您在 shell 中创建了 Foo ,也可以确保创建 Bar 。

    @receiver(post_save, sender=Foo)
    def create_bar_on_foo_created(sender, instance=None, created=False, **kwargs):
        if created:
            Bar.objects.get_or_create(foo=instance)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2014-01-09
      • 2019-06-26
      相关资源
      最近更新 更多