Sunday, June 14, 2015

Re: How to serialize one record with Django / REST?

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

On Jun 14, 2015 11:37 AM, "Daniel Grace" <danwgrace@gmail.com> wrote:
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.

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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.

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CA%2Be%2BciUWtkWSRAcEpmkDMJbqbAOPEQYcFT7BQE%2B%3Dpnv_pZSs1w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment