我在表单中有一个名为q
的搜索字段。当我搜索某个成员时,我希望它像下面一样过滤
results = Member.objects.filter(Q(mid=q) | Q(mobile=q)).order_by('pub_date')
在其他形式中,我想做类似的事情 如:
Account.objects.filter(Q(name=q)|Q(card=q)).order_by('pub_date')
我需要exactly equal filter
,因此使用django-haystack
是过度的。
简单的基本形式:
class SimpleSearchForm(forms.Form):
q = forms.CharField(required=False)
search_fields = []
def __init__(self, model=None):
super(SimpleSearchForm, self).__init__()
if not model:
raise Exception('SimpleSearchForm need init with a model')
self.model = model
def search(self):
q = self.cleaned_data['q']
if len(self.search_fields) > 0:
# construct a Q() statement, filter result and return
但我不知道如何构造这样的Q()语句。
答案 0 :(得分:1)
为了制作动态Q()语句,您可以使用强大的** kwargs功能。 要动态进行以下查询:
results = Member.objects.filter(Q(mid=q) | Q(mobile=q))
以下是代码:
from django.db.models import Q
import operator
predicates = [('mid', q), ('mobile', q)] # You may form this list dynamically as per your requirement
q_list = [Q(x) for x in predicates] # generates a list of Q objects dynamically
results = Member.objects.filter(reduce(operator.or_, q_list)) # to combine all Q objects, reduce and operator python methods are used
通过这种方式,您可以进行动态查询
有关详细说明,请访问here