【问题标题】:Django tastypie filter boolean fieldDjango 美味派过滤布尔字段
【发布时间】:2014-03-15 00:24:32
【问题描述】:

我在models.py中有课:

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 模板中有这个无线电组:

<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>

我想使用 jquery 序列化()radiogroup 并发送到tastepie API 以从模型中获取过滤数据:

来自查询的 URL 将如下所示:

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

结果将仅显示 is_active 字段中具有 False 值的行

如果我使用 ?is_active=1 结果将只有 True

如何从表中获取 True 和 False 行?

我可以更改输入中的“名称”属性,但所有输入中的名称必须相同才能保持分组。

【问题讨论】:

    标签: django boolean filtering tastypie


    【解决方案1】:

    如果您在 Django 端传递 ?is_active=,则请求将在 POST 字典中包含“is_active”:

    >>> '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)
    

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 2014-01-12
      • 2012-12-17
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多