I'm going through django tutorial and having the TypeError 'method' object is not subscriptable. The error is thrown when the following code executed
class ProductListView(ListView):
model = Product
queryset = Product.objects.all()
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args, **kwargs)
context["now"] = timezone.now()
context["query"] = self.request.GET.get["q"]
return context
def get_queryset(self, *args, **kwargs):
print(self.request)
qs = super(ProductListView, self).get_queryset(*args, **kwargs)
query = self.request.GET.get["q"]
if query:
qs = self.model.objects.filter(
Q(title__icontains=query) |
Q(description__icontains=query)
)
try:
qs2 = self.model.objects.filter(
Q(price=query)
)
qs = (qs | qs2).distinct()
except:
pass
return qs
The problem line is query = self.request.GET.get["q"]
How do I solve this issue?
The Python "TypeError: 'method' object is not subscriptable" occurs when we use square brackets instead of parentheses to call a method. To solve the error, use parentheses when calling functions or methods, e.g. object. method() .
An object can only be subscriptable if its class has __getitem__ method implemented. By using the dir function on the list, we can see its method and attributes. One of which is the __getitem__ method. Similarly, if you will check for tuple, strings, and dictionary, __getitem__ will be present.
Python TypeError: 'int' object is not subscriptableThis error occurs when you try to use the integer type value as an array. In simple terms, this error occurs when your program has a variable that is treated as an array by your function, but actually, that variable is an integer.
In simple words, objects which can be subscripted are called sub scriptable objects. In Python, strings, lists, tuples, and dictionaries fall in subscriptable category.
The problematic line tries to use subscript notation with method get
of the mapping GET
:
query = self.request.GET.get["q"]
The method should be called with:
query = self.request.GET.get("q")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With