【问题标题】:Flask SQLAlchemy - StaticMethod vs Custom Querying ClassFlask SQLAlchemy - 静态方法与自定义查询类
【发布时间】:2017-08-25 18:24:29
【问题描述】:

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

这是我的事件模型类:

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”类分配给模型的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()

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

【问题讨论】:

  • 按什么指标? 1 可能更直接,更容易维护
  • 我看到很多人在这里推荐创建自定义查询类,正如我在第二种方式中展示的那样,所以我徘徊是否有实际原因......当然第一种方式更简单所以为什么有这么多关于这个“不必要的”自定义查询功能的文档?

标签: python flask model flask-sqlalchemy


【解决方案1】:

对于一个简单的孤立示例,我认为这并不重要。对于更大更复杂的情况,选项 2 提供了额外的灵活性,可以将您的过滤器与其他过滤器结合起来。

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

诚然,您可以修改选项 1,使其将查询作为参数并返回一个新查询,但随后它开始看起来与典型的 SQLAlchemy 查询完全不同。

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 1970-01-01
    • 2013-04-02
    • 2018-05-09
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2013-07-24
    相关资源
    最近更新 更多