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
closed! i have problem solved! Thank you everyone.
and
If you want to create several new items you should instantiate the serializer by yourself and add the argument
many=True