2016-10-02 91 views
1

的Django 1.10.1链接过滤器

在我已经准备了很多控件的页面。其中一些被组织为动态变化的表单集。所以,我甚至不知道他们中有多少人。

我需要用AND,OR和NOT逻辑操作的链接过滤器。

例如,我需要的是这样的:

Entry.objects.filter(headline__startswith='What').exclude(pub_date__gte=datetime.date.today()).filter(pub_date__gte=datetime(2005, 1, 30)).filter(Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) 

再次过滤器的数量正在改变。

我正打算AC这样的:通过request.POST循环,并根据条件十几准备的字符串。相同的字符串:

"Entry.objects.filter(headline__startswith='What').exclude(pub_date__gte=datetime.date.today()).filter(pub_date__gte=datetime(2005, 1, 30)).filter(Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))"

因此,该字符串是正确的。但是我不能使它与exec()一起工作。 我在这里问:为什么它不工作。答案是:它不会工作,直接运行Python代码。

我可以构建这样的事情:

entries = Entry.objects.filter(**kwargs) 

但是,这仅仅是一个过滤器。我无法想象如何链接这样的过滤器。

你能帮助我在这里&

+0

我想知道你的'POST'请求​​是什么样的。 – demux

回答

0

你可以链上的多行查询集 - 将取决于视图逻辑附加查询。这些查询集只有在被调用时才会在创建时执行。

我不知道这是否是“最佳”或最Python的方式,但像这样的作品对我非常好。这是使用Django的REST框架辅助方法,但应不适用:

def get(self, request, format=None, *args, **kwargs): 
     name = request.GET.get('name', None) 
     location = request.GET.get('location', None) 
     id = request.GET.get('id', None) 

     results = Model.objects.all().order_by('-created') # this would be the default with no filters on it 
     results = results.filter(name__iexact=name) if name else results 
     results = results.filter(location__icontains=location) if location else results 
     results = results.filter(id__exact=id) if id else results 

     # process/serialize/send response 

不知道哪些参数,你会得到可能会非常棘手,但一个想法可能是循环在你的kwargs并按照相同的模式循环 - 这里是刺(注意我还没有测试过):

def get(self, request, format=None, *args, **kwargs): 

     results = Model.objects.all().order_by('-created') # this would be the default 
     for param, value in kwargs.items(): 
      results = results.filter(***need to convert param to orm field***= value) 
+0

工作。但链接OR运算符仍然存在问题。我需要像Article.objects.filter( Q(title__icontains =“table”)| Q(title__icontains =“helm”) )。那么,这是一个问题 - 语法是过滤器(** kwargs)。但如何通过这个“我”? – Michael

+0

你能跟随类似的模式吗? http://stackoverflow.com/a/852481/4396787 –

+0

非常感谢你。 – Michael