- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
很多时候,我写了如下查询:
pony.orm.select(u for u in User if u.available and u.friends > 0 and ...)
所以,我想编写我自己的 select
版本,作为它的替代品。像是避免我每次都写谓词的第一部分,if u.available and u.friends > 0
。
我的问题更笼统:我如何编写一个像 select
这样的函数,它接受像 select
方法或 count
方法那样的参数可以接受。
最佳答案
让我们按以下方式定义一个 User
实体:
from datetime import datetime, timedelta
from pony.orm import *
db = Database('sqlite', ':memory:')
class User(db.Entity):
username = Required(str, unique=True)
password = Required(str)
friends = Set("User", reverse='friends') # many-to-many symmetric relation
online = Required(bool, default=False) # if user is currently online
last_visit = Optional(datetime) # last visit time
disabled = Required(bool, default=False) # if user is disabled by administrator
sql_debug(True)
db.generate_mapping(create_tables=True)
现在我们可以定义一些方便的函数来检索最常用的用户类型。第一个函数将返回未被管理员禁用的用户:
def active_users():
return User.select(lambda user: not user.disabled)
在该函数中,我使用 User
实体的 select
方法接受 lambda 函数,但可以使用全局 select
编写相同的函数接受生成器表达式的函数:
def active_users():
return select(u for u in User if not user.disabled)
active_users
函数的结果是一个查询对象。您可以调用filter
查询对象的方法来产生更具体的查询。例如,我可以使用 active_users
函数来选择名称以“A”字母开头的活跃用户:
users = active_users().filter(lambda user: user.name.startswith('A')) \
.order_by(User.name)[:10]
现在我想找到最近几天访问该网站的用户。我可以定义另一个函数,它使用从前一个函数返回的查询并按以下方式扩充它:
def recent_users(days=1):
return active_users().filter(lambda u: u.last_visit > datetime.now() - timedelta(days))
在这个例子中,我将 days
参数传递给函数,并在过滤器中使用它的值。
您可以定义一组这样的函数,它们将构成您应用程序的数据访问层。更多示例:
def users_with_at_least_n_friends(n=1):
return active_users().filter(lambda u: count(u.friends) >= n)
def online_users():
return User.select(lambda u: u.online)
def online_users_with_at_least_n_online_friends(n=1):
return online_users().filter(lambda u: count(f for f in u.friends if f.online) >= n)
users = online_users_with_at_least_n_online_friends(n=10) \
.order_by(User.name)[:10]
在上面的示例中,我定义了全局函数。另一种选择是将这些函数定义为 User
实体的类方法:
class User(db.Entity):
username = Required(str, unique=True)
...
@classmethod
def name_starts_with(cls, prefix):
return cls.select(lambda user: not user.disabled
and user.name.startswith(prefix))
...
users = User.name_starts_with('A').order_by(desc(User.last_visit))[:10]
如果您可能想要一个可以应用于不同实体类的通用函数,那么您需要将实体类作为参数传递。例如,如果许多不同的类具有 deleted
属性,并且您希望有一个通用方法来仅选择未删除的对象,您可以这样写:
def select_active(cls):
return cls.select(lambda obj: not obj.deleted)
select_active(Message).filter(lambda msg: msg.author == current_user)
上面提供的所有函数都有一个缺点——它们不可组合。您不能从一个函数获取查询并用另一个函数扩充它。如果你想拥有一个可以扩充现有查询的函数,该函数应该接受查询作为参数。示例:
def active_users():
return User.select(lambda user: not user.disabled)
def name_starts_with(query, prefix):
return query.filter(lambda user: user.name.startswith('prefix'))
name_starts_with
函数可以应用于另一个查询:
users1 = name_starts_with(active_users(), 'A').order_by(User.last_visited)
users2 = name_starts_with(recent_users(), 'B').filter(lambda user: user.online)
我们还致力于查询扩展 API,这将允许程序员编写自定义查询方法。当我们发布此 API 时,可以通过以下方式将自定义查询方法链接在一起:
select(u for u in User).recent(days=3).name_starts_with('A')[:10]
希望我回答了你的问题。如果是这种情况,请接受正确答案。
关于python - 为自定义 Pony 编写选择函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32130920/
我有 2 个表。 TableA & TableB TableA +------+----------------+-----------+ | id | some_attribute | tabl
我正在尝试学习 Pony,出于显而易见的原因,我想做的第一件事就是打印值。 但是,它似乎不适用于大多数事情,例如: env.out.print(2 + 2) 给出错误: Could not infer
Pony 有一个未参数化的异常值。 不幸的是,我经常有一些代码想要抛出不同类型的异常,并且我需要知道它们是什么,以便正确处理它们——例如,简单地说,当停止程序时,向用户提供以下信息很重要正确的错误消息
我已经安装了pony.vim 我找不到任何文档来阅读如何使用它。我通过 vundle 安装它 gmarik vundle 如果我输入其中任何一个,我也不会得到任何帮助 :helptags pony :
执行 Pony ORM 查询并尝试按模型上存在的三个属性对查询进行排序。首先是歌曲类型,它可以是 ssf_type_order_map 中列出的五个值之一,然后是持续时间 (int) 和 uuid (
假设我用 pony.orm 映射了这些表: class Category(db.Entity): threads = Set("Thread") class Thread(db.Entity)
我想使用 pony orm 测试一张表是否为空。 起初我连接到数据库并说生成映射。我在这里使用“名称”表作为示例并连接到 postgres 数据库 from pony.orm import * cla
我正在尝试使用 Pony ORM 将多个值插入到我的 postgres 数据库中。我目前的方法效率很低: from pony.orm import * db = Database() class Na
很多时候,我写了如下查询: pony.orm.select(u for u in User if u.available and u.friends > 0 and ...) 所以,我想编写我自己的
Pony ORM将生成器表达式转换为 SQL 是一个不错的技巧。示例: >>> select(p for p in Person if p.name.startswith('Paul'))
我最近开始使用 Pony ORM,我认为它非常棒。尽管 API 在官方网站上有详细记录,但我在处理关系方面遇到了困难。特别是我想插入一个作为集合一部分的新实体。但是,我似乎无法找到一种在不先获取相关对
我尝试在 pony orm 中使用 order_by 聚合实现一个简单的选择: 所以,我尝试了以下方法:第一种方式引发错误信息: sel = select((f.Name, f.id) for f i
假设我在 Pony ORM 中有以下架构: from pony.orm import * db = Database("postgres", database='foo') class Job(db.
Pony ORM 的分页有什么最佳实践吗? 我看到其他人有这些 has_next 和 has_previous 辅助方法,但在 Pony 中我只能靠自己。 到目前为止,这就是我所拥有的,几个 Jinj
我正在评估从 peewee 到 Pony ORM 的转换。 peewee 中提供的一件好事是能够从这样的部分组成查询: def Entry(BaseModel): # peewee field
我无法让小马工作。现在我收到一个错误: TypeError: wrong argument (NilClass)! (Expected kind of OpenSSL::SSL:SSLContext)
我有一张报名表,要求填写人员姓名和电子邮件地址。我将该电子邮件地址保存到 session 中,以便在提交表单后访问它。然后我使用 Pony 向提交表单的人发送一封感谢/通知电子邮件。但是,虽然它可以毫
我想使用 Pony 邮件从我的 ruby 脚本发送一封电子邮件。当我为 gmail smtp 设置它时,它工作正常。当我将其设置为使用我们的 ISP 的 SMPT 时,出现此错误。 iiNet 代
我正在寻找的是具有计算机视觉经验的人关于哪种方法或算法最适合解决这个特定问题的建议。我是一位经验丰富的程序员(主要是 .NET),但我对计算机视觉几乎一无所知,我想节省时间。 我更喜欢不需要大型训练集
将带有附件(html 文件)的电子邮件发送到 gmail 时,不会发送电子邮件正文。如果我注释掉下面的附件设置就可以了。如果电子邮件没有任何附件,那就没问题。 我测试发现,只有当文件扩展名为“html
我是一名优秀的程序员,十分优秀!