如何在查询中传递列名动态?

时间:2013-11-19 12:30:55

标签: python django django-models django-queryset

我的查询

col_name=('parole_state', 'hiv_treatment_state', 'receiving_hiv_treatment', 'mental_health_provider', 'employed', 'parole', 'employer_state')

qs_new = Model_Name.objects.all().values(col_name)

获取错误:'tuple' object has no attribute 'split'使用此追溯

  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 884, in _setup_query
    self.query.add_fields(self.field_names, True)

  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1580, in add_fields
    name.split(LOOKUP_SEP), opts, alias, False, allow_m2m,

AttributeError: 'tuple' object has no attribute 'split'

1 个答案:

答案 0 :(得分:2)

你需要解压缩元组:

qs_new = Model_Name.objects.all().values(*col_name)

这会将列名称直接传递为values('a', 'b', 'c'),而不是values(('a', 'b', 'c'))。因此,这就是为什么您目前收到的错误split()无法在元组上调用。