2014-02-15 91 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很多,它的工作原理! –