简体   繁体   中英

Empty user id for many value in child table

I have a problem in sqlalchemy. I have one to many relationship:

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    tags = relationship('Tag', back_populates='users')

class Tag(Base):
    __tablename__ = 'tags'

    id = Column(Integer, primary_key=True)
    tag_name = Column(String(50))
    user_id = Column(Integer, ForeignKey('users.id'))
    users = relationship('User', back_populates='tags')

When i save tags in this way

user = session.query(User).filter(User.id == user_id).first()
user.tags = [Tag(tag_name=tag_name)]
session.add(user)
session.commit()

All tags saved but when o opened my db i see that only for last tag have value of user id and for other tags this filed empty. 在此处输入图像描述 But test must have user_id =1. How can i fixed this problem? For framework i use sanic and db is posgresql. I want to save for user with id =1 many tags like: [user_id=1, tag='tad1'], [user_id=1, tag='tad2'] and [user_id=1, tag='tad3']. As a result i have may users but each users have own multiple tags.

It is difficult to tell, because you are not showing the full context in which you are adding multiple tags, but if you are using something like this:

def add_tag(user_id,tag_name):
  user = session.query(User).filter(User.id == user_id).first()
  user.tags = [Tag(tag_name=tag_name)]
  session.add(user)
  session.commit()

ANd then executing it like this:

for tag in tags:
  add_tag(user_id=user.id,tag_name=tag.name)

Then because you use user.tags = [Tag(tag_name=tag_name)], you would be overwriting all previous tags rather than appending to them. This would explain why only the last tag appears to be connected to the user. To append new tags rather than overwriting you should use append() like so:

def add_tag(user_id,tag_name):
  user = session.query(User).filter(User.id == user_id).first()
  user.tags.append(Tag(tag_name=tag_name))
  session.add(user)
  session.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM