2017-04-04 5 views
0

나는 사용자 테이블과 앨범 테이블 등이 있고 사용자 앨범은 1 - 많은 관계가 있습니다.플라스크 - sqlalchemy, 하나 - 많은 관계, NULL로 외래 키 변경

그러나 사용자가 하나 이상의 앨범과 연결하면 앨범 테이블에서 최신 외래 키를 제외하고 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() 

내가 당신이 그것을 다른 할 필요가 있다고 생각하는 이유 ..

+0

게시자가 테이블에 데이터를 게시하는 방법과 관련된 코드를 게시 할 수 있습니까?, 어떻게 업데이트합니까? 사용자 및 앨범 테이블? –

+0

(처음에는 누가 세션중인 사용자 'u'를 찾았습니다.) u.albums = [Album (title = request.json [ 'title'], created_at = datetime.utcnow())]; db_session.add (u); db_session.commit(); –

+0

나는 앨범 목록을 무시하고, 다른 방법으로 앨범을 만들고 앨범을 만든 다음 Album.user_uid = u.uid를 할당하는 것이 좋다고 생각합니다. –

답변

1

몰라 귀하의 방식대로 사용자의 앨범 목록을 무시하고 있습니다.

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() 
+0

훌륭한 솔루션입니다. 고맙습니다. – joshlsullivan