Sqlalchemy的`hybrid_property`问题

时间:2018-09-12 12:44:59

标签: python sqlalchemy

我正在尝试实现一个混合属性,该属性将允许我通过用户的当前订阅来查询该用户。

我在UserSubscription模型下定义了is_expired属性。然后,我意识到它必须是混合属性,才能在类级别上查询。但这仍然行不通。

该错误消息位于代码段的底部。

''' Models '''
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String, unique=True)
    subscriptions = db.relationship(
        'UserSubscription', back_populates='user'
    )

    @property
    def current_subscription(self):
        try:
            return UserSubscription.query.filter_by(user_id=self.id, is_active=True, is_expired=False).one()
        except NoResultFound:
            return None

class UserSubscription(db.Model):
    __tablename__ = 'user_subscription'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    subscription_id = db.Column(db.Integer, db.ForeignKey('subscription.id'), default=0) # 0 for free

    subscribed_on = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
    is_active = db.Column(db.Boolean, nullable=False, default=True)

    user = db.relationship('User', back_populates='subscriptions')
    subscription = db.relationship('Subscription', back_populates='users')

    @hybrid_property
    def subscription_expiry(self):
        return datetime.timedelta(days=self.subscription.expiry_time) + self.subscribed_on

    @hybrid_property
    def is_expired(self):
        if self.subscription_expiry <= datetime.datetime.now(): return True
        else: return False


>>> my_user.current_subscription
E           sqlalchemy.exc.InvalidRequestError: Entity '<class 
'.models.UserSubscription'>' has no property 'is_expired'

0 个答案:

没有答案