我正在开发一种功能,我需要能够将包含属性的列表发布到API。酒店有name
,value
和unit
。现在我有两个问题:
many = True
一样简单,我在这里做:(由于某种原因,除非我在这里放置文字,否则代码不会格式化)
class PropertyViewSet(viewsets.ModelViewSet):
queryset = Property.objects.all()
serializer_class = PropertySerializer
所以我尝试了serializer = PropertySerializer(queryset, many=True)
,它破坏了API视图。所以我想我必须创建一个新的序列化器并为此查看(我是对的)?但是,如何确保我的API知道在合适的时间使用哪一个?
如果有人能澄清这将是伟大的,谢谢。
ModelViewSet
类提供了create()
方法,它只允许您一次创建一个对象。见docs
如果要POST对象列表并将每个对象插入数据库,则必须创建自定义视图。例如
from rest_framework.decorators import api_view
from django.shortcuts import redirect
from .models import MyModel
@api_view(['POST'])
def insert_list(request):
if request.method == 'POST':
for obj in request.POST['list']: #assuming you are posting a 'list' of objects
MyModel.objects.create(name=obj.name, value=obj.value, unit=obj.unit)
return redirect('url of MyObject List View')
要在视图集旁边使用自定义API视图,只需将自定义API视图添加到视图集网址未使用的其他网址,例如如果您的视图集使用r'^myModel/$'
,则使用r'^myModel/insert_list/$'
作为createlist自定义APIview
如果你需要创建对象,我就是这样做的:
# Mixin that allows to create multiple objects from lists.
class CreateListModelMixin(object):
def get_serializer(self, *args, **kwargs):
""" if an array is passed, set serializer to many """
if isinstance(kwargs.get('data', {}), list):
kwargs['many'] = True
return super(CreateListModelMixin, self).get_serializer(*args, **kwargs)
然后在视图中你想要只使用它:
class PropertyCreateView(CreateListModelMixin, generics.CreateAPIView):
serializer_class = PropertySerializer
permission_classes = (IsAuthenticated, )
这已经是它了(确保在视图之前将mixin作为参数放入;就像我做的那样)。
现在你的postrequest的主体看起来像这样:
{
[
{
"name": "<some_name>"
"value": "<some_value>"
"unit": "<some_unit>"
},
{
"name": "<some_name>"
"value": "<some_value>"
"unit": "<some_unit>"
},
{
"name": "<some_name>"
"value": "<some_value>"
"unit": "<some_unit>"
},
...
]
}
关于它的很酷的事情,这样你也可以像这样发布一个对象:
{
"name": "<some_name>"
"value": "<some_value>"
"unit": "<some_unit>"
}
我希望这有帮助! :)
在模型中定义一个新字段,如下所示,
from django.db import models
from jsonfield import JSONField
class Property(models.Model):
name = models.CharField(max_length=120)
age = models.IntegerField()
address = models.CharField(max_length=100)
my_list = JSONField(default=[]) # new field
然后更改序列化器,如下所示,
from rest_framework import serializers
class SampleSerializer(serializers.ModelSerializer):
my_list = serializers.ListField()
class Meta:
fields = '__all__'
model = PropertySerializer
要通过Property
创建一个REST Api
实例,请使用此json
{
"my_list": ["a","b","c"],
"name": "my_name",
"age": 30,
"address": "my address"
}