2014-02-15 161 views
1

我有類models.py:Django的tastypie過濾器布爾字段

class Companies(models.Model): 
    id = models.AutoField(unique=True, primary_key=True, null=False, blank=False) 
    is_active = models.BooleanField(default=1, editable=False) 

在HTML模板中有這樣的RadioGroup中:使用jQuery我想要序列()RadioGroup中,發送給tastypie

<fieldset> 
    <legend>Status</legend> 
    <input type="radio" name="is_active" value="">All</label> 
    <input type="radio" name="is_active" value="True" checked="1">Active</label> 
    <input type="radio" name="is_active" value="False">Not Active</label> 
    </fieldset> 

API以從模型中獲得過濾數據:

查詢的URL然後將如下所示:

http://localhost:8000/api/view/company/list/?is_active=

結果將會顯示在IS_ACTIVE場

如果我使用值僅排?IS_ACTIVE = 1個結果將只有

我怎樣才能既真和假表表中的行?

我可以在輸入中更改「名稱」屬性,但名稱在所有輸入中必須保持相同。

回答

1

如果在Django的一側通過?is_active=請求將有「IS_ACTIVE」在POST詞典:

>>> 'is_active' in request.POST` 
True 

的問題是內容的字符串,是空的位置:

>>> request.POST['is_active'] 
'' # Or None I am not quite sure. 

而且根據Python語義:

>>> bool(None) 
False 
>>> bool(False) 
False 
>>> bool(0) 
False 
>>> bool('') 
False 

所有負值都是:[](){}set()0''NoneFalse

您必須覆蓋build_filters如果空刪除此鍵或不叫API與值是空的。

def build_filters(self, filters=None): 
    if filters is None: 
     filters = {} 

    if "is_active" in filters and filters["is_active"] == '': # or == None you have to check 
     del filters['is_active'] 

    return super(MyResource, self).build_filters(filters) 
+0

thx很多,它的工作原理! –