Em quinta-feira, 20 de abril de 2017 23:18:03 UTC-3, Robin Lery escreveu:
>
> I have a very simple model and its related serializer and views:
>
> class Page(models.Model):
>     user = models.ForeignKey(User)
>     title = models.CharField(max_length=255)
>     pub_date = models.DateTimeField(default=timezone.now)
>
> class PageSerializer(serializers.ModelSerializer):
>     class Meta:
>         model = Page
>         fields = ('user', 'title', 'pub_date')
>
> class PageViewSet(viewsets.ModelViewSet):
>     queryset = Page.objects.all()
>     serializer_class = PageSerializer
> Now I can post like this:
>
> {
>     "user": 1,
>     "title": "Lorem ipsum"
> }
> This works fine. But I would like to post multiple objects like this:
>
> [
>     {
>         "user": 1,
>         "title": "Lorem ipsum one"
>     },
>     {
>         "user": 1,
>         "title": "Lorem ipsum two"
>     }
> ]
> But this gives me an error:
>
> "non_field_errors": [
>
> "Invalid data. Expected a dictionary, but got list."
> ]
> So to accept multple objects I modified the view as per the doc:
>
> class PageViewSet(viewsets.ModelViewSet):
>     queryset = Page.objects.all()
>     serializer_class = PageSerializer(queryset, many=True)
>
> But I am getting an error:
>
> TypeError at /api/blog/pages/
>
> 'ListSerializer' object is not callable
> What am I missing here?
>

You can do this overriding get_serializer method: 

def get_serializer(self, *args, **kwargs):
if "data" in kwargs:
data = kwargs["data"]

# check if many is required
if isinstance(data, list):
kwargs["many"] = True

return super(YourModel, self).get_serializer(*args, **kwargs)  

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a1811b72-a91d-4ab8-9b26-4c293c4e7ddd%40googlegroups.com.

Reply via email to