gpt4 book ai didi

python - ponyORM:查询有问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:29 24 4
gpt4 key购买 nike

我有动态条件查询,即

select (lambda obj:obj.A = 'a' and obj.B = 'b' and ...)  

所以我为此编写代码:

def search(self,**kwargs):
q = unicode('lambda obj:', 'utf-8')
for field,value in kwargs.iteritems():
value = unicode(value, 'utf-8')
field = unicode(field, 'utf-8')
q+=u" obj.%s == '%s' and" % (field,value

q = q[0:q.rfind('and')]
res = select(q.encode('utf-8'))[:]

但是我在执行函数的过程中出现了这个错误:

 tasks.search(title='Задача 1',url='test.com')
res = select(q.encode('utf-8'))[:]
File "<string>", line 2, in select
File ".../local/lib/python2.7/site-packages/pony/utils.py", line 96, in cut_traceback
return func(*args, **kwargs)
File ".../local/lib/python2.7/site-packages/pony/orm/core.py", line 3844, in select
if not isinstance(tree, ast.GenExpr): throw(TypeError)
File "...local/lib/python2.7/site-packages/pony/utils.py", line 123, in throw
raise exc
TypeError

最佳答案

虽然可以使用字符串来将条件应用于查询,但它可能不安全,因为存在 SQL 注入(inject)的风险。将条件应用于查询的更好方法是使用 filter() 方法。您可以从 https://github.com/ponyorm/pony 获取最新版本的 Pony ORM存储库并尝试下面提供的几个示例。

首先我们定义实体并创建几个对象:

from decimal import Decimal
from pony.orm import *

db = Database('sqlite', ':memory:')

class Product(db.Entity):
name = Required(unicode)
description = Required(unicode)
price = Required(Decimal)
quantity = Required(int, default=0)

db.generate_mapping(create_tables=True)

with db_session:
Product(name='iPad', description='Air, 16GB', price=Decimal('478.99'), quantity=10)
Product(name='iPad', description='Mini, 16GB', price=Decimal('284.95'), quantity=15)
Product(name='iPad', description='16GB', price=Decimal('299.00'), quantity=10)

现在我们将应用过滤器将它们作为关键字参数传递:

def find_by_kwargs(**kwargs):
q = select(p for p in Product)
q = q.filter(**kwargs)
return list(q)

with db_session:
products = find_by_kwargs(name='iPad', quantity=10)
for p in products:
print p.name, p.description, p.price, p.quantity

另一种选择是使用 lambda 来指定条件:

def find_by_params(name=None, min_price=None, max_price=None):
q = select(p for p in Product)
if name is not None:
q = q.filter(lambda p: p.name.startswith(name))
if min_price is not None:
q = q.filter(lambda p: p.price >= min_price)
if max_price is not None:
q = q.filter(lambda p: p.price <= max_price)
return list(q)

with db_session:
products = find_by_params(name='iPad', max_price=400)
for p in products:
print p.name, p.description, p.price, p.quantity

如您所见,可以动态应用过滤器。您可以通过以下链接找到有关使用过滤器的更多信息:http://doc.ponyorm.com/queries.html#Query.filter

关于python - ponyORM:查询有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23203960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com