Reputation: 4141
I get following error:
AttributeError at /filterrule/createresultset/
'dict' object has no attribute 'filter_query_json'
Here's the code:
from django.db import connections
def fetch_filter_rule_sql_from_ui_db(filter_rule_id):
with connections['frontend'].cursor() as cursor:
query = "SELECT id, filter_query_json FROM dmf_filter_rules WHERE id=%s LIMIT 1"
cursor.execute(query, [filter_rule_id])
filter_rule_sql_json = dictfetchall(cursor)[0].filter_query_json
# filter_rule_sql_json = dictfetchall(cursor)[0][filter_query_json]
return filter_rule_sql_json
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
The output to dictfetchall(cursor)[0]
is:
{
"id": 1,
"filter_query_json": "{\"request_id\":\"341\",\"match_status\":\"1\",\"verdict\":\"Non Match\",\"matched\":\"s_vs_r_image_class_match\"}"
}
Object looks fine to me and I confirmed the filter_query_json
attribute too.
What is missing?
Upvotes: 0
Views: 5755
Reputation: 94
You can only get the straight value if the object is the built-in dict
type. To fix this, the solution can be
filter_rule_sql_json = dictfetchall(cursor)[0].get('filter_query_json')
If your key filter_query_json
does not exist, the method .get(key)
would return None
.
Upvotes: 2
Reputation: 2011
change your line to filter_rule_sql_json = dictfetchall(cursor)[0]['filter_query_json']
athough I would recommend using django's database api rather than writing raw sql queries
Upvotes: 1