Flask SQLAlchemy - StaticMethod vs Custom Querying Class

时间:2017-08-25 18:24:29

标签: python flask model flask-sqlalchemy

我的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 个答案:

答案 0 :(得分:3)

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

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

不可否认,您可以修改选项1,以便将查询作为参数并返回一个新查询,但是它会开始看起来与典型的SQLAlchemy查询完全不同。