我刚开始使用python和django,并寻找迭代对象属性的可能性,以实现所有字段的搜索功能。
diff对象类继承自抽象基类,我创建了一个可搜索的静态函数,它应该返回可以搜索的属性。
class Item(BaseItem):
internal_ean = models.CharField(unique=True, max_length=20)
quantity = models.IntegerField(default=1)
@staticmethod
def searchable():
return ['ean', 'internal_ean', 'brand', 'model']
不,我想做那样的事情:
for key in Item.searchable():
try:
string='{}={}'.format(key,term)
my_list.extend(getattr(Item.objects, "filter")(string))
except (Item.DoesNotExist):
pass
我可以做些什么来避免评估和类似的东西?有没有办法返回我可以直接使用的指针或属性列表?
从django我回来了:
ValueError: too many values to unpack
答案 0 :(得分:3)
qdict = dict.fromkeys(Item.searchable(), term)
rquery = Item.objects.filter(**qdict)
答案 1 :(得分:2)
考虑以下代码:
from django.db.models import Q
def search_items_and_exact(term):
"""Returns items with all searchable attributes exactly equals to term"""
filters = {}
for search_attr in Item.searchable():
filters[search_attr] = term
return Item.objects.filter(**filters)
def search_items_or_exact(term):
"""Returns items with any searchable attributes exactly equals to term"""
q_seq = Q()
for search_attr in Item.searchable():
filters = {search_attr: term}
q_seq = q_seq | Q(**filters)
return Item.objects.filter(q_seq)
def search_items_and_contains(term, ignore_case=False):
"""Returns items with all searchable attributes contains term"""
if ignore_case:
contains = 'icontains'
else:
contains = 'contains'
filters = {}
for search_attr in Item.searchable():
filters["{0}__{1}".format(search_attr, contains)] = term
return Item.objects.filter(**filters)
def search_items_or_contains(term, ignore_case=False):
"""Returns items with any searchable attributes contains term"""
if ignore_case:
contains = 'icontains'
else:
contains = 'contains'
q_seq = Q()
for search_attr in Item.searchable():
filters = {"{0}__{1}".format(search_attr, contains): term}
q_seq = q_seq | Q(**filters)
return Item.objects.filter(q_seq)