sqlalchemy 1 to many relationship

拥有回忆 提交于 2019-12-24 21:26:20

问题


i tried to implement a simple sqlalchemy table relationship

so, I have below model:

class User(db.Model):
    __tablename__ = "users"
    UserID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    FirstName = db.Column(db.String(255), nullable=False)
    LastName = db.Column(db.String(255), nullable=False)

    #others column

    Tokens = db.relationship('Token', backref='Token.UserID', primaryjoin='User.UserID==Token.UserID', lazy='dynamic')

    #bla... other codes

and

class Token(db.Model):
    __tablename__ = "user_tokens"
    TokenID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    UserID = db.Column(db.Integer, db.ForeignKey('users.UserID'))
    Token = db.Column(db.String(255), nullable=False)

    #others column

    #bla... other codes

and I do query:

user = User.query.filter(User.UserID).first()

problem: when i tried to access:

print(user.Tokens.UserID)
# or
print(user.Tokens.Token)

I always received:

'AppenderBaseQuery' object has no attribute 'UserID' / 'Token'

What am I missing here?

来源:https://stackoverflow.com/questions/44607363/sqlalchemy-1-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!