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)
謝謝! 是的,我想過濾潛在值的列表。 該解決方案效果很好。 – Archarachne