sqlalchemy Error creating backref on relationship

后端 未结 2 1643
北荒
北荒 2021-02-07 07:46

I have two very simple models. In my Post model there are supposed to be two relationships into the User table. One is for the owner of the post and on

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 07:59

    The error is telling you that you've used post as a name more then once for your backrefs, all you need to do is give the backref's unique names. Here's a complete example-- I've added a id primary key to the Post class, and also some __repr__s so we get some readable output.

    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, BigInteger, ForeignKey, Integer
    from sqlalchemy.orm import relationship, sessionmaker
    
    Base = declarative_base()
    engine = create_engine('sqlite://') ## In Memory.
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()
    
    class Post(Base):
        __tablename__ = 'post'
        id = Column(Integer, primary_key=True)
        last_editor_id = Column(BigInteger, ForeignKey('users.id'), nullable=True)
        last_editor = relationship('User', backref='editor_posts', foreign_keys=[last_editor_id])
        owner_id = Column(BigInteger, ForeignKey('users.id'), nullable=False, index=True)
        owner = relationship('User', backref='owner_posts', foreign_keys=[owner_id])
    
        def __repr__(self):
            return ''.format(self.id)
    
    
    class User(Base):
        '''This represents a user on the site'''
        __tablename__ = 'users'
        id = Column(BigInteger, primary_key=True, unique=True)
        name = Column(BigInteger, nullable=False)
    
        def __repr__(self):
            return ''.format(self.name)
    
    
    
    Base.metadata.create_all(engine)
    
    bob = User(name='Bob', id=1)
    alice = User(name='Alice', id=2)
    post = Post(owner=alice, last_editor=bob, id=1)
    
    session.add(post)
    session.commit()
    
    bob = session.query(User).get(1)
    print bob
    # 
    print bob.editor_posts
    # []
    print bob.owner_posts
    # []
    
    post = session.query(Post).get(1)
    print post.owner
    # 
    print post.last_editor
    # 
    

    Now when you query a user, you can ask that object user.owner_posts or user.editor_posts.

提交回复
热议问题