可以有条件地链接WHERE子句吗?

huangapple go评论60阅读模式
英文:

Can I chain where clauses conditionally?

问题

在我的DAO API层中,我广泛使用Peewee作为ORM,并且需要在条件下使查询变得更窄,例如:

query = UserModel.select().where(UserModel.last_name == last_name)
if first_name is not None:
   query = query.where(UserModel.first_name == first_name)

# ... 更多条件然后

df = pd.DataFrame(query.dicts())

这是在Peewee中以最符合惯例的方式进行条件查询窄化的方法吗?还有其他方法吗?这样做有什么优缺点吗?

英文:

I'm using Peewee as ORM extensively and within my DAO API layer I need to conditionally make a query narrower e.g.

query = UserModel.select().where(UserModel.last_name == last_name)
if first_name is not None:
   query = query.where(UserModel.first_name == first_name)

# ... more conditions then

df = pd.DataFrame(query.dicts())

is this the most idiomatic way to conditionally make the queries narrower in Peewee or is there another way? Are there any pros and cons of doing this?

答案1

得分: 1

我建议首先处理动态条件,然后调用where子句。

query = UserModel.select()
filtered = UserModel.last_name == last_name

if first_name is not None:
   filtered &= UserModel.first_name == first_name
   
# ... 更多条件接着写

# 如果有一些条件:
#    filtered &= some_other_cond

# 如果有一些条件:
#    filtered |= some_other_cond
 
# 根据您的函数逻辑选择其中之一 

query = query.where(filtered)

df = pd.DataFrame(query.dicts())
英文:

I would suggest to doing first the dynamic condition and then calling where clause.

query = UserModel.select()
filtered = UserModel.last_name == last_name

if first_name is not None:
   filtered &= UserModel.first_name == first_name
   
# ... more conditions then

# if some_cond:
#    filtered &= some_other_cond

# if some_cond:
#    filtered |= some_other_cond
 
# put one or other depending on
# the logic of your function 

query = query.where(filtered)

df = pd.DataFrame(query.dicts())

Edit : fix an error in the code

答案2

得分: 1

Sure you can do this a couple ways:

# Chaining calls to .where() will AND the clauses together.
q = q.where(Model.field == 'something')
q = q.where(Model.other == 'another')

# Another option:
accum = []
accum.append(Model.field == 'something')
accum.append(Model.other == 'another')
q = q.where(*accum)

# Or you can explicitly AND them together:
q = q.where(reduce(operator.and_, accum))

Etc.

英文:

Sure you can do this a couple ways:

# Chaining calls to .where() will AND the clauses together.
q = q.where(Model.field == 'something')
q = q.where(Model.other == 'another')

# Another option:
accum = []
accum.append(Model.field == 'something')
accum.append(Model.other == 'another')
q = q.where(*accum)

# Or you can explicitly AND them together:
q = q.where(reduce(operator.and_, accum))

Etc.

huangapple
  • 本文由 发表于 2023年7月17日 14:44:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702040.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定