django - 删除字段名称和括号

时间:2014-01-06 14:56:31

标签: django

我有以下查询集 -

pk = Jobmst.objects.db_manager('database1').extra(where=['jobmst_alias=%s'], params=[alias]).values('jobmst_id')

返回以下内容 -

[{'jobmst_id': 21195}]

编辑 -

pk = Jobmst.objects.db_manager('database1').extra(where=['jobmst_alias=%s'], params=[alias]).values_list('jobmst_id', flat=True)

返回以下内容 -

[21195]

关闭,但我不想要括号,我只想要整数。

我希望它只是给我一个整数值,所以我可以在另一个查询中调用它 -

mst = Jobmst.objects.db_manager('database1').raw("""
    SELECT jobmst_id, jobmst_type, jobmst_prntname AS jobmst_prntid, jobmst_active,
    evntmst_id, jobmst_evntoffset, jobmst_name, jobmst_mode, jobmst_owner, jobmst_desc,
    jobmst_crttm, jobdtl_id, jobmst_lstchgtm, jobmst_runbook, jobcls_id, jobmst_prntname,
    jobmst_alias, jobmst_dirty FROM Jobmst WHERE jobmst_id = %s""", [pk])

理想情况下,这会解析 -

mst = Jobmst.objects.db_manager('database1').raw("""
    SELECT jobmst_id, jobmst_type, jobmst_prntname AS jobmst_prntid, jobmst_active,
    evntmst_id, jobmst_evntoffset, jobmst_name, jobmst_mode, jobmst_owner, jobmst_desc,
    jobmst_crttm, jobdtl_id, jobmst_lstchgtm, jobmst_runbook, jobcls_id, jobmst_prntname,
    jobmst_alias, jobmst_dirty FROM Jobmst WHERE jobmst_id = 21195""")

1 个答案:

答案 0 :(得分:1)

values返回dicts列表,因此您可以按列表索引和键名访问值:

try:
    pk = Jobmst.objects.db_manager('database1').extra(where=['jobmst_alias=%s'],
        params=[alias]).values('jobmst_id')[0]['jobmst_id']
except IndexError:
    pk = None

您可以使用仅返回指定字段值列表的values_list并访问您只需索引的值:

try:
    pk = Jobmst.objects.db_manager('database1').extra(where=['jobmst_alias=%s'],
        params=[alias]).values_list('jobmst_id', flat=True)[0]
except IndexError:
    pk = None