带附加列的flask-sqlalchemy查询关联表

时间:2019-02-08 13:45:22

标签: flask many-to-many flask-sqlalchemy

我按照下面的代码创建了多对多关系,但是我在关联表中添加了其他列。我想按特定的用户ID检索这些列。有人可以建议如何查询吗?我读了很多帖子,但是没有一个专栏。

如果我这样做:

u = Users.query.filter_by(id='8').first()
u.subscriptions[0].id

我可以从“订阅”表中看到数据,但是如果这样做:

u.subscriptions[0].subscription_id
OR
u.subscriptions[0].User_Subscription

我正在获取“ Subscription”对象没有属性,因为我正在尝试获取User_Subscription关联表中的列数据。

User_Subscription = db.Table('user_subscription', 
    db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
    db.Column('subscription_id', db.Integer, db.ForeignKey('subscription.id')),
    db.Column('stripe_subscription_id', db.String(100), nullable=True),
    db.Column('paypal_subscription_id', db.String(100), nullable=True)
)

class Subscription(db.Model):
    __tablename__ = "subscription"
    id = db.Column(db.Integer, primary_key=True)
    subscription_name = db.Column(db.String(100), unique=True, nullable=False)
    subscription_desc = db.Column(db.String(100), unique=False, nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    date_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
    subscriptions = db.relationship('Users', secondary=User_Subscription, backref= db.backref('subscriptions', lazy='dynamic'))

class Users(db.Model, UserMixin):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String(50), unique=False, nullable=False)
    lastname = db.Column(db.String(50), unique=False, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    date_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
    user_status_id = db.Column(db.String(2), db.ForeignKey('user_status.id'))

1 个答案:

答案 0 :(得分:0)

您遇到错误(“订阅”对象没有属性),因为它是关系对象,而不是表。

在这一行代码中:

u.subscriptions[0].User_Subscription

您正在尝试访问对象User_Subcription的属性,该对象是关系对象。

如果要创建新的关联表,请在数据库中创建相同的表,然后再定义一个类UserSubscription:

class UserSubscription(db.Model)
    __tablename__ = 'user_subscription'
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    subscription_id = db.Column(db.Integer, db.ForeignKey('subscription.id'))
    stripe_subscription_id = db.Column(db.String(100), nullable=True)
    paypal_subscription_id = db.Column(db.String(100), nullable=True)

    user = db.relationship('Users', backref='user_subscription')

然后您可以访问UserSubscription类的属性:

u.user_subscription.subscription_id