python - flask-sqlalchemy,一对多关系,外键变为NULL

标签 python mysql foreign-keys one-to-many flask-sqlalchemy

我有用户表和相册表等..并且用户相册具有一对多关系。

但是当用户关联一个或多个相册时,相册表中排除最新相册的外键将变为 null。 This is the case that user_uid=1 have 3 albums and user_uid=2 have 1 album.(BUT foreign key having user_uid=1 is only just one.而且这个问题也存在于具有一对多关系的任何地方。这是我的代码..

class User(Base):
__tablename__ = 'user'

uid = Column(Integer, primary_key=True)
username = Column(String(10), unique=True, nullable=False)
email = Column(String(35), unique=True, nullable=False)
salted_password = Column(String(100), unique=True, nullable=False)
profile_pic = Column(String(100))
authorization = Column(Boolean)
expiry = Column(DATETIME)
fcm_token = Column(String(45))
created_at = Column(DATETIME)
albums = relationship('Album')
notifications = relationship('Notification')
like_photo = relationship('Photo', secondary=like_photo)
follow_album = relationship('Album', secondary=follow_album)
followed = relationship('User',
                           secondary=followers,
                           primaryjoin=(followers.c.follower_id == uid),
                           secondaryjoin=(followers.c.followed_id == uid),
                           backref=backref('followers', lazy='dynamic'),
                           lazy='dynamic')
comment_photo = relationship('Photo', secondary=comment)




class Album(Base):
__tablename__ = 'album'

aid = Column(Integer, primary_key=True)
title = Column(String(45), nullable=False)
created_at = Column(DATETIME)
user_uid = Column(Integer, ForeignKey('user.uid'))
photos = relationship('Photo')
album_tags = relationship('Album_tag')

我更新了专辑表,如下所示..

u = User.query.filter(User.uid == session['uid']).first()
u.albums = [Album(title=request.json['title'], created_at=datetime.utcnow())]               
db_session.add(u) 
db_session.commit()

不知道为什么..

最佳答案

我相信您需要以相反的方式进行操作,因为按照您的方式,您将覆盖用户的相册列表:

coffee_album = Album(title=request.json['title'], \
                     created_at=datetime.utcnow())
u = User.query.filter(User.uid == session['uid']).first()
coffe_album.user_uid = u.uid
db_session.add(coffee_album) 
db_session.commit()

关于python - flask-sqlalchemy,一对多关系,外键变为NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43200698/

相关文章:

php - 将产品添加到购物车时出错

python - Pandas 根据 Name 列创建 Foreign ID 列

python - 在其方法之外引用一个类?

python - Python 中的 MySQL 查询

c# - 从多个文本框中选择查询c#

mysql - Amazon Aurora RDS 无法使用导入文件。 Mysql Workbench 中的用户访问被拒绝

php - 外键、连接和返回索引

java - 如何解决 "Cannot add or update a child row: a foreign key constraint fails"

python - 将 LMDB 复制到另一个 LMDB 可减少文件大小

python - 如何更改BeautifulSoup的解析器?