'Category' object is not subscriptable Django

Question:

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

Asked By: Matteo Possamai

||

Answers:

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.

Answered By: michjnich

it’s a simple mistake.

Simply change it as follows and it should be fixed:

categories = request.data.get('categories')
for category in categories:
    category_obj = Category.objects.get(id=category['id'])
    category_obj.isActive = category['isActive']
    category_obj.save()

What you’re doing is changing what the variable category is. You for loop and the unpacked variable is category, but then you get the model object and set the variable as category

So initially, the category variable is in fact a dictionary object, but you change it to be a django model object instance.

Answered By: Swift
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.