[Answered ]-'Category' object is not subscriptable Django

1👍

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.

👤Swift

0👍

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.

Leave a comment