SQLAlchemy过滤实例属性的方法

时间:2016-01-18 04:52:18

标签: sqlalchemy flask-sqlalchemy

我有UserExpense个类。单个用户有一个费用清单。我想添加一个属性current_expenses,它只返回当月的费用清单。显然,我可以这样做:

class User(db.Model):

    ...

    def current_expenses():
        now = datetime.datetime.now()
        db.session.query(Expense)\
            .filter(User.name = self.name)\
            .filter(db.extract('year', Expense.date_time) == now.year)\
            .filter(db.extract('month', Expense.date_time) == now.month)
        ...

但这似乎很愚蠢,因为SQLAlchemy已经有一个与用户实例相关的费用列表。有没有更好的方法来检索这些数据?

1 个答案:

答案 0 :(得分:2)

如果要对用户的费用进行查询,可以将关系配置为class Expense(Base): __tablename__ = 'expense' id = Column(Integer, primary_key=True) amount = Column(Integer) user_id = Column(Integer, ForeignKey('user.id')) date_time = Column(DateTime, default=datetime.datetime.now) class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) expenses = relationship("Expense", lazy='dynamic') @hybrid_property def current_expenses(self): now = datetime.datetime.now() ret = self.expenses.filter(extract('month', Expense.date_time) == now.month).all() return ret e1 = Expense(amount=400) e2 = Expense(amount=300) u1 = User() u1.expenses = [e1, e2] session.add(u1) print u1.current_expenses ,这将返回用户费用的查询对象。

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    expenses = relationship("Expense")

    @hybrid_property
    def current_expenses(self):
        now = datetime.datetime.now()
        ret = [e for e in self.expenses if e.date_time.month == now.month]

        return ret

或者,如果您使用默认的预先加载,则只需过滤附加到模型实例的Python费用列表。

{{1}}