Thursday, April 20, 2017

Re: Django rest framework cannot deal with multple objects in model viewset


Le 21 avr. 2017 à 04:17, Robin Lery <robinlery@gmail.com> a écrit :

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?

it's serializer_class, not serializer_instance. You can't instantiate the serializer there.
In order to deal with multiples items, you better override the `list` method to handle multiple objects creation and have an explicit serializer instantiation.

Regards,
Xavier Ordoquy,
Linovia.


No comments:

Post a Comment