Django REST framework JSON array post

2019-06-09 14:26发布

I'm using Django 1.8 and Django rest_framework 3.3.1. I can save a single JSON array and it works. But I want to save multiple JSON arrays.

I have found a solution for the request, ㅠ

How can I save this JSON array?

Test JSON array:

{
    "urllist": [
        {
          "title": "20151123100000011",
          "publisher": "01100101",
          "link": "01100101.20151123100000011"
        },
        {
          "title": "20151123100000076",
          "publisher": "01100101",
          "link": "01100101.20151123100000076"
        }
      ]
}

Model:

class NewsUrl(models.Model):
    link = models.CharField(max_length=100, primary_key=True)
    title = models.TextField(default='')
    publisher = models.CharField(max_length=150, blank=True, default='')
    status = models.CharField(max_length=1, default='R')  # R:Ready, W:Working, D:Done
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return "NewsUrlList = [%s] %s" % (self.link, self.title)

    class Meta:
        ordering = ('created', )

View:

class NewsUrlList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = NewsUrl.objects.all()
    serializer_class = NewsUrlSerializer
    permission_classes = (IsAuthenticated, )
    authentication_classes = (JSONWebTokenAuthentication, )

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

Serializer:

class NewsUrlSerializer(serializers.Serializer):
     link = serializers.CharField(required=True, max_length=100)
     title = serializers.CharField(required=False, max_length=200)
     publisher = serializers.CharField(required=False, max_length=10)
     status = serializers.CharField(required=False, default='R')

     def create(self, validated_data):
         return NewsUrl.objects.create(**validated_data)

     def update(self, instance, validated_data):
         instance.status = validated_data.get('status', instance.status)
         instance.save()
         return instance

2条回答
一夜七次
2楼-- · 2019-06-09 14:59

closed! i have problem solved! Thank you everyone.

def post(self, request, *args, **kwargs):
    urls = request.data["urls"]

    is_many = isinstance(urls, list)
    if not is_many:
        return super(NewsUrlList, self).create(request, *args, **kwargs)
    else:
        serializer = self.get_serializer(data=urls, many=True)
        serializer.is_valid(raise_exception=True)
        self.create_list(serializer)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

and

def create_list(self, serializer):
    for new_link in serializer.data:
        NewsUrl.objects.create(**new_link)
查看更多
贪生不怕死
3楼-- · 2019-06-09 15:10

If you want to create several new items you should instantiate the serializer by yourself and add the argument many=True

查看更多
登录 后发表回答