我有一个用户类,详情如下:
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.Unicode(length=128), unique=True)
username = db.Column(db.Unicode(length=128), unique=True)
_password = db.Column("password", db.String(length=60))
admin = db.Column(db.Boolean, default=False)
joined = db.Column(db.DateTime, default=datetime.utcnow)
confirmed = db.Column(db.Boolean, default=False)
profile_picture = db.Column(db.Unicode(length=128), unique=True, nullable=True)
twitter = db.Column(db.Unicode(length=256), unique=True, nullable=True)
github = db.Column(db.Unicode(length=256), unique=True, nullable=True)
我想在用户类中添加另一列,这是一个用户列表。我怎么能做到这一点?
我认为我所寻找的正确名称是一种自我参照的一对多关系。
答案 0 :(得分:1)
根据您的评论,您希望存储一个关联表,该关联表存储哪个用户跟随哪个用户。这就是所谓的多对多关系。由于用户可以关注许多其他用户,因此许多用户可以跟随用户。
为此我们需要定义一个附加表,并 relationship
(http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many)来指定该表的用法,例如:
class UserFollows(db.Model):
__tablename__ = 'user_follows'
follower = Column(Integer, ForeignKey('users.id'))
followee = Column(Integer, ForeignKey('users.id'))
现在我们可以为User
类定义两个虚拟列,并指定SQLAlchemy应该查看user_follows
表:
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.Unicode(length=128), unique=True)
username = db.Column(db.Unicode(length=128), unique=True)
_password = db.Column("password", db.String(length=60))
admin = db.Column(db.Boolean, default=False)
joined = db.Column(db.DateTime, default=datetime.utcnow)
confirmed = db.Column(db.Boolean, default=False)
profile_picture = db.Column(db.Unicode(length=128), unique=True, nullable=True)
twitter = db.Column(db.Unicode(length=256), unique=True, nullable=True)
github = db.Column(db.Unicode(length=256), unique=True, nullable=True)
followers = db.relationship('User',
secondary = followers,
primaryjoin = (UserFollows.c.follower == id),
secondaryjoin = (followers.c.followee == id))
follows = db.relationship('User',
secondary = followers,
primaryjoin = (UserFollows.c.followee == id),
secondaryjoin = (followers.c.follower == id))
现在,User
对象有两个属性followers
和follows
,它们充当用户的集合,用于存储User
follows
以及followers
的{{1}}。