2014-01-24 73 views
0

我有一個小問題。如何過濾查詢字符串列表?

我有一個模型Person和一個列表:fields = ['firstname','age']。現在

,我想遍歷字段列表,做這樣的事情:

people = Person.objects.all() #this is just to start 
people_filtered = people.filter(firstname__icontains='ohn') 

我知道的方法

f = Person._meta.get_field('firstname') 

,並返回我場的一個實例

<django.db.models.fields.CharField: firstname> 

,但把它像這樣:

people.filter(f__icontains='ohn') 

Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 667, in filter 
    return self._filter_or_exclude(False, *args, **kwargs) 
    File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 685, in _filter_or_exclude 
    clone.query.add_q(Q(*args, **kwargs)) 
    File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1259, in add_q 
    can_reuse=used_aliases, force_having=force_having) 
    File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1127, in add_filter 
process_extras=process_extras) 
    File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1325, in setup_joins 
    "Choices are: %s" % (name, ", ".join(names))) 
FieldError: Cannot resolve keyword 'f' into field. Choices are: age, firstname, id, lastname 

如何從這個字段得到'__icontains'的結果我希望是什麼?

class Person(models.Model): 
    firstname = models.CharField(null=False, blank=False, max_length=32) 
    lastname = models.CharField(null=False, blank=False, max_length=32) 
    age = models.IntegerField(null=False, blank=False, max_length=8) 

回答

1

你指的是什麼字符串列表?潛在值列表或過濾器/參數列表?

如果你想要的關鍵字/過濾器是動態的,然後做一些像

key = '%s__icontains' % firstname 

people.filter(**{key:'ohn'}) 

應該工作

如果你希望值是動態的,那麼這可能會奏效:

values = ['ohn', 'john', 'doe'] 

people.filter(firstname__icontains__in = values) 

我不知道你是否可以鏈接像icontains和像這樣的SQL功能,但也許你可以。我相信我們不是第一個想到這個的人。

+0

謝謝! 是的,我想過濾潛在值的列表。 該解決方案效果很好。 – Archarachne