How to serialize one record with Django / REST?

136 views
Skip to first unread message

Daniel Grace

unread,
Jun 14, 2015, 2:37:14 PM6/14/15
to django...@googlegroups.com
I can serialize all objects using the following.  In views:

class ProductDetail(generics.ListAPIView):
    serializer_class = ProductSerializer
    def get_queryset(self):
        return Product.objects.all()

In serializers:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('code', 'name', 'description')

When I try to restrict this to one record, I get an error:

class ProductDetail(generics.RetrieveAPIView):
    serializer_class = ProductSerializer
    def get_queryset(self):
        pid = int(self.kwargs['pid'])
        return Product.objects.get(id=pid)

Exception Type: AttributeError
Exception Value:'Product' object has no attribute 'model'

I am guessing that get_queryset is not the right thing to use in this situation.

James Schneider

unread,
Jun 14, 2015, 3:24:10 PM6/14/15
to django...@googlegroups.com

Instead of using .get(), try using .filter() instead, since get_queryset() needs to return a query set and not the actual object (even though the query set will only contain a single result).

Your code for the get_queryset() override is actually better suited as an override for get_object() in the view itself.

I think you can get away without the overrides entirely if you set 'pk_url_kwarg = "pid" ' (without the single quotes) on your detail view, and you should be able to use the same serializer for both your list and detail views.

-James

--
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...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1a4a658e-4728-4577-a0f6-9fdd5e110f09%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages