Home > database >  'Category' object is not subscriptable Django
'Category' object is not subscriptable Django

Time:12-06

I am learning Django. I wrote a simple model and some views method in Django rest framework so that I can modify some particular attributes when needed to all the records that need that. Here is the model:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=255)
    isActive = models.BooleanField(default=True)

    def __str__(self):
        return self.name

Then, I created this view to modify the isActive session when I call it:

class CategoriesChangeActiveView(views.APIView):
    def post(self, request, format=None):
        try:
            categories = request.data.get('categories')
            for category in categories:
                category = Category.objects.get(id=category['id'])
                category.isActive = category['isActive']
                category.save()
        except Exception as e:
            return Response({'error': 'Bad request'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'success': 'Active changed'}, status=status.HTTP_200_OK)

Even when the format of my request is correct ( I debugged each line ) when it comes to the line category.isActive = category['isActive']it throws the error that'Category' object is not subscriptable`. I don't know why or how to fix it.

I saw in the official documentation, on older StackOverflow questions that this is doable, but I don't understand why I can't.

Can someone please suggest what I am doing wrong? Thank you

CodePudding user response:

If you see the error "'Category' object is not subscriptable" in Django, it means that you are trying to use the square bracket notation (e.g. category[0]) on a Category object, but this notation is not supported by the Category class.

In Django, the square bracket notation is used to access the elements of a QuerySet, which is a list-like object that represents a collection of database records. However, a Category object represents a single record in the database, not a collection of records, so you cannot use the square bracket notation on it.

To access the properties of a Category object, you can use the dot notation (e.g. category.name) instead. This will allow you to access the individual fields of the Category object, such as its name or its id.

CodePudding user response:

Specifically, the issue is here:

category = Category.objects.get(id=category['id'])
category.isActive = category['isActive']

You set category to be an instance of the Category model (which in this case corresponds to a db record, but that bit is a little irrelevant).

Accessing attributes on a class instance is not done by the square bracket notation, but rather dot notation.

So instead of category['isActive'] use category.isActive

If category was a dictionary, eg.

category = {
    "name": "cat",
    "isActive": True,
}

Then you would use the square bracket notation as category["isActive"] to get that value.

As it is, it's not a dict, so python thinks you are trying to subscript the instance somehow, which will not work.

  • Related