【问题标题】:Select all fields that are true选择所有正确的字段
【发布时间】:2013-04-08 02:06:54
【问题描述】:

我有一个用户数据库和一个水果数据库,用户填写一个复选框来选择他们有什么水果。

我想在个人资料中反映此信息,但我不知道如何在 web2py 中查询数据库以显示所有设置为 True 的布尔字段。

可以通过 SQL 查询来完成,还是我需要过滤选择用户水果记录的结果?

这是我的数据库模型:

db.define_table('fruit',
    Field('id', 'reference auth_user'),
    Field('apple','boolean',label=T('Apple')),
    Field('apricot','boolean',label=T('Apricot')),
    Field('cherry','boolean',label=T('Cherry')),
    Field('fig','boolean', label=T('Fig')),
    Field('lychee','boolean', label=T('Lychee')),
    Field('peach','boolean', label=T('Peach')),
    Field('pear','boolean', label=T('Pear')),
    Field('plum','boolean', label=T('Plum')))

这是我的控制器(显然它不起作用。它只返回<Set 0>)。

我尝试了几种不同的谷歌搜索组合,但都没有达到预期的结果:

def profile():

    id = auth.user.id or redirect(URL('default', 'index'))
    user = db.auth_user[id]
    fruit = db.fruit(id=id)
    produce = db(fruit == True)
    return dict(user=user, produce=produce)

【问题讨论】:

    标签: web2py


    【解决方案1】:
    fruit = db.fruit(id=id)
    

    在上面,fruit 是一个 DAL Row 对象(其行为很像字典)。

    produce = db(fruit == True)
    

    上面,db(fruit == True) 是您指定 DAL 集的方式,fruit == True 部分将是 DAL 查询,但在查询中使用 Row 对象没有意义。在任何情况下,您都不需要 Set 对象,因为此类对象不包含任何数据——它们仅定义一组记录(不检索它们)。

    目前尚不清楚您要查找的数据结构类型,但如果您想要已检查的水果名称列表,您可以尝试:

    produce = [field for field in fruit if fruit[field] is True]
    

    上面的列表解析遍历字段名称并保留与字段关联的值为True的那些(这将自动跳过任何非布尔字段,因为只有布尔字段存储实际值TrueFalse)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 2016-12-21
      • 2021-11-19
      • 2021-02-25
      • 1970-01-01
      相关资源
      最近更新 更多