How do I refer to a foreign key table twice?

2020-04-21 01:57发布

I get the following error:

u'detail': u"One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Could not determine join condition between parent/child tables on relationship Vote.user - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table."

Table A is being defined as:

class User(postgres.Model):

    def __init__(self,
        name
    ):
        self.name = name

    id = postgres.Column(postgres.Integer , primary_key=True , autoincrement=True)
    name = postgres.Column(postgres.String(32) , nullable=False , unique=True)

Table B is being defined as:

class Vote(postgres.Model):

    def __init__(self,
        user_id,
        responder_id,
        #timestamp_request,
        #timestamp_respond,
        value 
    ):
        self.user_id = user_id
        self.responder_id = responder_id
        #self.timestamp_request = timestamp_request
        #self.timestamp_respond = timestamp_respond
        self.value = value

    id = postgres.Column(postgres.Integer , primary_key=True , autoincrement=True)
    user_id = postgres.Column(postgres.Integer , postgres.ForeignKey('user.id'))
    user = postgres.relationship(User , backref=postgres.backref('votes_user'))
    responder_id = postgres.Column(postgres.Integer , postgres.ForeignKey('user.id'))
    responder = postgres.relationship(User , backref=postgres.backref('votes_responder'))
    timestamp_request = postgres.Column(postgres.DateTime , default=datetime.datetime.utcnow , nullable=False , unique=False)
    timestamp_respond = postgres.Column(postgres.DateTime , default=datetime.datetime.utcnow , onupdate=datetime.datetime.utcnow , nullable=False , unique=False)
    value = postgres.Column(postgres.Enum('up' , 'down' , name='vote_value_enum') , nullable=True)

1条回答
老娘就宠你
2楼-- · 2020-04-21 02:45

SQLAlchemy is unable to discover the relationship path.

user_id = Column(ForeignKey('user.id'))
user = relationship(User, backref=backref('votes_user'))
responder_id = Column(ForeignKey('user.id'))
responder = relationship(User, backref=backref('votes_responder'))

Do the responder relationship must join using responder_id or user_id? I know it is obvious to us, but SQLAlchemy don't consider column names here. You can rename responder_id as foobar and it'll make no difference.

Define the foreign keys you want to use for each relationship.

user = relationship(User, foreign_keys=[user_id], backref=backref('votes_user'))
responder = relationship(User, foreign_keys=[responder_id], backref=backref('votes_responder'))
查看更多
登录 后发表回答