gpt4 book ai didi

python - Flask SQLAlchemy - StaticMethod 与自定义查询类

转载 作者:太空狗 更新时间:2023-10-30 00:09:18 24 4
gpt4 key购买 nike

我有一个包含 start_datedue_date 列的 Event 模型。我想创建一种简单的方法来获取所有事件事件(已经开始但尚未完成)。

这是我的事件模型类:

class Event(db.Model):
__tablename__ = 'events'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(254))
description = db.Column(db.Text)
start_date = db.Column(db.DateTime)
due_date = db.Column(db.DateTime)

我熟悉满足此需求的两种可行解决方案:

1:使用staticmethod 函数,它将对 Event.query 对象进行所有筛选并返回事件事件的完整列表

class Event(BaseModel):
...
@staticmethod
def get_active():
return Event.query.filter(...).all()

# Usage:
records = Event.get_active()

2:通过创建一个继承自BaseQuery的新查询对象,并将这个新的“EventQuery”类分配给Model的query_class成员。

class EventQuery(BaseQuery):
def get_active(self):
return self.filter(...)

class Event(BaseModel):
__tablename__ = 'events'
query_class = EventQuery
....

# Usage:
Event.query.get_active().all()

所以我想知道,哪种方法更好/推荐?

最佳答案

对于一个简单的孤立示例,我认为这无关紧要。对于更大更复杂的案例,选项 2 提供了额外的灵 active ,可以将您的过滤器与其他过滤器结合使用。

Event.query.filter_by(user_id=1).get_active().all()

不可否认,您可以修改选项 1,使其将查询作为参数并返回一个新查询,但这样一来它就会开始看起来与典型的 SQLAlchemy 查询截然不同。

关于python - Flask SQLAlchemy - StaticMethod 与自定义查询类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45887449/

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