python AttributeError 'dict' 对象没有属性

python AttributeError 'dict' object has no attribute

我收到以下错误:

AttributeError at /filterrule/createresultset/
'dict' object has no attribute 'filter_query_json'

代码如下:

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()
    ]

dictfetchall(cursor)[0] 的输出是:

{
    "id": 1,
    "filter_query_json": "{\"request_id\":\"341\",\"match_status\":\"1\",\"verdict\":\"Non Match\",\"matched\":\"s_vs_r_image_class_match\"}"
}

对象对我来说很好,我也确认了 filter_query_json 属性。

少了什么?

如果对象是内置的int,你只能得到直接值dictype。要解决此问题,解决方案可以是

filter_rule_sql_json = dictfetchall(cursor)[0].get('filter_query_json')

如果您的密钥 filter_query_json 不存在,方法 .get(key) 将 return None.

将您的线路更改为 filter_rule_sql_json = dictfetchall(cursor)[0]['filter_query_json']

尽管我建议使用 django 的数据库 api 而不是编写原始 sql 查询