Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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(country=cartorder.country).exists() 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

tax_rate_fee = TaxRate.objects.filter(country=cartorder.country).exists()
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(country=cartorder.country)
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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading