otakumike
otakumike

Reputation: 175

Using ModelSerializer with DRF and Class-based View returns Attribute Error

I've just started working with DRF and I'm finding myself struggling a bit. I'm attempting to create a class-based view that uses a model serializer. However, no matter what I try I keep getting this error:

'QuerySet' object has no attribute 'code'

My model does have this attribute, and I've confirmed that the query set (when dumped as values) also has this attribute.

models.py

class Category(models.Model):
    code = UUIDField(unique=True)
    name = models.CharField(max_length=100, null=True, blank=True, unique=True)
    parent_cat = models.ForeignKey('self', null=True, blank=True)

    def __unicode__(self):
        return self.name

urls.py

urlpatterns = patterns('', url(r'^', views.CatView.as_view()))

views.py

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category 

class CatView(APIView):
    def get(self, request, format=None):        
        queryset = Category.objects.all()
        serialized = CategorySerializer(queryset)

        return Response(serialized.data)

If I dump the output of the Category.objects.all() call I see the following data:

[{'id': 1, 'code': '7889022e-4e03-4c27-860a-f07c2477db0c', 'parent_cat_id': None, 'name': 'Women'}, {'id': 2, 'code': '167c2578-b747-41f5-b2ad-1aa7e3f63952', 'parent_cat_id': 1, 'name': 'Clothing'}, {'id': 3, 'code': '176e0db1-1a4a-4cd3-a6f3-0cac07ab748c', 'parent_cat_id': 1, 'name': 'Dresses'}]

So I can at least validate that the data is coming out of my model correctly. However, when I try to return the response, I see the following error:

AttributeError at /category/ 
'QuerySet' object has no attribute 'code'

From everything I can see, I can tell that it does have that attribute. Where have I gone wrong?

Upvotes: 0

Views: 356

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599600

The error message is correct: a QuerySet doesn't have a code attribute, only the individual Category instances do.

When you pass a queryset to a serialised rather than an instance, you need to tell it that you're giving it a collection, as shown in the tutorial:

serialized = CategorySerializer(queryset, many=True)

You really should go through that tutorial: as well as showing you what you were doing wrong, it goes on to show you much better ways of dong the same thing (by using mixins or generic views).

Upvotes: 2

Related Questions