我的 Flask-SQLAlchemy 项目的用户模型中有以下关系字段,我希望能够设置默认值,以便用户自动关注自己。有没有办法在 SQLAlchemy 中的关系中设置默认值?那会是什么样子?
followed = db.relationship('User', secondary=followers, primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'),
lazy='dynamic')
下面的函数是这样的:
def follow(self, user):
# returns an object if it succeeds, None if it fails
if not self.is_following(user):
self.followed.append(user)
return self
我一直在使用 Miguel Grinberg 的教程作为参考,但我的项目设置为我无法像他那样在 after_login 中执行 db.session.add(user.follow(user)) 。我之前在 before_first_request 中做过,但是单元测试有问题,因为用户没有登录,因此是匿名的。让用户在初始化时默认遵循自己的行为可以解决这个问题。感谢您的帮助!
您的用户模型添加新方法。
@staticmethod
def follow():
if not user.is_following(user):
user.follow(user)
db.session.add(user)
db.session.commit()
我也有类似的问题:
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(30), nullable=False)
full_name: Mapped[str] = mapped_column(String, nullable=False)
is_online: Mapped[bool] = mapped_column(Boolean, default=True)
followings: Mapped["list[User]"] = relationship( # !!!problem is here!!!!
"User",
secondary="follower_associations",
primaryjoin="User.id == FollowerAssociation.follower_id",
secondaryjoin="User.id == FollowerAssociation.following_id",
uselist=True
)
class FollowerAssociation(Base):
__tablename__ = "follower_associations"
id: Mapped[int] = mapped_column(primary_key=True)
follower_id: Mapped[int] = mapped_column(ForeignKey(
User.id,
name="fk_follower_id",
ondelete="CASCADE"
))
following_id: Mapped[int] = mapped_column(ForeignKey(
User.id,
name="fk_following_id",
ondelete="CASCADE"
))
follower: Mapped[User] = relationship(User, foreign_keys=[follower_id])
following: Mapped[User] = relationship(User, foreign_keys=[follower_id])
更改后问题解决了:
followings: Mapped["list[User]"] = relationship(
到
followings: Mapped[list["User"]] = relationship(