Ich habe Benutzer Tabelle und Album Tabelle usw. .. und Benutzer-Album haben eine-viele-Beziehung.flask-sqlalchemy, eine-viele-Beziehung, Fremdschlüssel ändert sich in NULL
Wenn jedoch ein Benutzer mit einem oder mehreren Alben verknüpft ist, ändert sich der Fremdschlüssel mit Ausnahme des letzten aus der Albumtabelle in 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. Und dieses Problem tritt auch überall mit einer-viele-Beziehung auf. Hier ist mein Code ..
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')
Und ich aktualisiert Album Tabelle wie unten ..
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()
Ich weiß nicht, warum ..
Können Sie Code im Zusammenhang mit, wie Sie Daten an Ihre Tabellen zu buchen ?, Wie Sie aktualisieren Benutzer- und Album-Tabellen? –
(Zuerst finde ich Benutzer 'u', der in Sitzung ist) u.albums = [Album (title = request.json ['title'], created_at = datetime.utcnow())]; db_session.add (u); db_session.commit(); –
Ich denke, dass Sie die Liste der Alben überschreiben, besser umgekehrt, erstellen Sie Album, und weisen Sie dann seine Album.user_uid = u.uid –