0

我刚开始使用 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

我能做些什么来避免 eval 和类似的东西?有没有办法返回我可以直接使用的指针或属性列表?

从 django 我回来了:

ValueError: too many values to unpack
4

2 回答 2

3
qdict = dict.fromkeys(Item.searchable(), term)
rquery = Item.objects.filter(**qdict)
于 2013-07-09T08:15:28.693 回答
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)
于 2013-07-09T08:19:08.987 回答