我有用戶表和專輯表等等。而用戶相冊有一對多的關係。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()
我不知道爲什麼..
你可以張貼代碼與你如何發佈數據到你的表嗎?用戶和專輯表? –
(首先我找到用戶'你'誰在會話中)u.albums = [專輯(標題= request.json ['標題'],created_at = datetime.utcnow())]; db_session.add(U); db_session.commit(); –
我認爲你這樣做是爲了覆蓋專輯列表,最好是用相反的方式來創建專輯,然後分配它的Album.user_uid = u.uid –