2016-10-02 74 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