如何过滤字符串列表上的查询?

时间:2014-01-24 10:47:23

标签: django django-models keyword

我有点问题。

我有一个模型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 个答案:

答案 0 :(得分:1)

你指的是什么字符串列表?潜在值列表或过滤器/参数列表?

如果您希望关键字/过滤器是动态的,请执行类似

的操作
key = '%s__icontains' % firstname

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

应该有效

如果您希望值是动态的,那么这可能有效:

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

people.filter(firstname__icontains__in = values)

我不确定你是否可以链接像icontains这样的sql函数,但也许你可以。我相信我们不是第一个想到这个的人

相关问题