2016-08-25 28 views
0

所以在我的模型中我有blank=True字段。我也有搜索這個模型,但是如果有一些字段是blank=True用戶不能填寫這個字段。如果某些字段爲空,我應該怎麼做?如何在django模型中搜索,如果不需要一些字段

例如我有姓名和姓氏(blank = True)的模型。如果姓氏不填寫搜索表單,我應該做一個過濾器,但如果姓氏是填充,我應該使姓氏過濾?

回答

0

那麼,我有一個非常嘲笑的情況。在我的模型中,我創建了一些字段blank=True,並忘記了makemigrations!所以不要忘記進行遷移

0

可以在部分建立一個QS:

def you_view(request, name, surname): 
    # ... Get you filter parameters, just an example. 
    qs = MyModel.objects.filter(name=name) 
    if surname: 
     qs = qs.filter(surname=surname) 
    # work with qs 

這將surname僅篩選如果在你看來一個surname變量。

1

當您必須從長表單數據列表中構建過濾器時,以下方法通常很方便。

import operator 
from django.db.models import Q 
filter_list = [Q(name=name)] 
if surname: 
    filter_list.append(Q(surname=surname)) 

YourModel.objects.filter(reduce(operator.and_, filter_list)) 
相關問題