How do I refer to a foreign key table twice?

余生颓废 提交于 2019-12-02 08:39:59

问题


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:


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'))


来源:https://stackoverflow.com/questions/36959083/how-do-i-refer-to-a-foreign-key-table-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!