Django: 'bool' object is not subscriptable when trying to get value from queryset

I am trying to get a value from a queryset, but i keep getting this error that says 'bool' object is not subscriptable.

I have a queryset that looks like this tax_rate_fee = TaxRate.objects.filter( and i am checking to see if a specific country exists in the Queryset, then i want to grab a value from the queryset and perform some operation.

This is my code

tax_rate_fee = TaxRate.objects.filter(
if tax_rate_fee:
    cartorderitem.vat = 5 * tax_rate_fee['rate']

this is the tax rate fee model

class TaxRate(models.Model):
    country = models.CharField(max_length=200)
    rate = models.IntegerField(default=5, help_text="Numbers added here are in percentage (5 = 5%)")
    active = models.BooleanField(default=True)

>Solution :

The reason you are getting the error ‘bool’ object is not subscriptable is that the exists() method on the queryset returns a boolean value indicating whether there are any records in the queryset that match the specified condition.

To retrieve the actual records from the queryset, you need to use the filter() or get() method instead of exists(). Also, once you have retrieved the records, you need to access the rate attribute of each record, not the boolean value returned by exists(). Here’s an example of how to modify your code:

tax_rate_fee = TaxRate.objects.filter(
if tax_rate_fee.exists():
    cartorderitem.vat = 5 * tax_rate_fee.first().rate

In this code, we first filter the TaxRate queryset to retrieve all records that match the specified country. We then check if there are any records using exists(). If there are, we retrieve the first record using first() (assuming there is only one matching record), and access its rate attribute to perform the calculation.

Note that if there are multiple matching records, you may want to use a different method to retrieve the appropriate record(s), such as get() or values().

Leave a Reply