且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Django Rest Framework创建多个模型实例?

更新时间:2023-01-09 16:36:32

我知道这是一段时间以前的问题,但是我试图找出这个自己。

事实证明,如果您在实例化一个模型的序列化器类时通过 many = True ,它可以然后接受多个对象。



这里提到这里



对于我的情况,我的视图看起来像这样: / p>

 类ThingViewSet(viewsets.ModelViewSet):
此视图提供列表,详细信息,创建,检索,更新
并销毁对事物的操作。
model = Thing
serializer_class = ThingSerializer

我真的不想去编写一个样板,只是直接控制串行器的实例化,并通过许多= True ,所以在我的序列化程序类中,我替代 __ init __

 类ThingSerializer(serializers.ModelSerializer):
def __init __(self,* args,** kwargs):
many = kwargs.pop('many',True)
super(ThingSerializer,self).__ init __(many = many,* args,** kwargs)

class Meta:
model = Thing
fields =('loads ','of','fields',)

将数据发布到此视图的列表网址格式:

  [
{'loaded':'foo','of':'bar'字段':'buzz'},
{'loaded':'fizz','of':'bazz','fields':'errrrm'}
]

创建了两个具有这些细节的资源。这是很好的。


I would like to save and update multiple instances using the Django Rest Framework with one API call. For example, let's say I have a "Clas-s-room" model that can have multiple "Teachers". If I wanted to create multiple teachers and later update all of their clas-s-room numbers how would I do that? Do I have to make an API call for each teacher?

I know currently we can't save nested models, but I would like to know if we can save it at the teacher level. Thanks!

I know this was asked a while ago now but I found it whilst trying to figure this out myself.

It turns out if you pass many=True when instantiating the serializer class for a model, it can then accept multiple objects.

This is mentioned here in the django rest framework docs

For my case, my view looked like this:

class ThingViewSet(viewsets.ModelViewSet):
    """This view provides list, detail, create, retrieve, update
    and destroy actions for Things."""
    model = Thing
    serializer_class = ThingSerializer

I didn't really want to go writing a load of boilerplate just to have direct control over the instantiation of the serializer and pass many=True, so in my serializer class I override the __init__ instead:

class ThingSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        many = kwargs.pop('many', True)
        super(ThingSerializer, self).__init__(many=many, *args, **kwargs)

    class Meta:
        model = Thing
        fields = ('loads', 'of', 'fields', )

Posting data to the list URL for this view in the format:

[
    {'loads':'foo','of':'bar','fields':'buzz'},
    {'loads':'fizz','of':'bazz','fields':'errrrm'}
]

Created two resources with those details. Which was nice.