SQLAlchemy中的关系无法按预期工作

时间:2018-11-16 22:42:46

标签: python sqlalchemy

我正在尝试在两个表之间创建一个关系;事件和位置。 我想要完成的事情是建立一对多的关系。可以在某个位置提供事件,因此该位置必须能够举行各种事件。我已经花了几个小时摆弄外键,但我不知道如何使它工作。

我的location.py看起来像这样:

from datetime import datetime

from sqlalchemy import Column, Integer, ForeignKey, Float, Date, String
from sqlalchemy.orm import relationship

from model import Base

class Location(Base):
    __tablename__ = 'location'
    id = Column(Integer, primary_key=True, nullable=False)
    title = Column(String, unique=True)
    description = Column(String, nullable=False)
    founder_id = Column(Integer, ForeignKey('users.id'))
    latitude = Column(Float)
    longtitude = Column(Float)
    creation_date = Column(Date, default=datetime.now)


    # Relationships
    creator = relationship('User', foreign_keys=founder_id)
    events = relationship('Event', back_populates='location')

和event.py看起来像这样:

from datetime import datetime

from sqlalchemy import Column, Integer, Date, Float, String, ForeignKey
from sqlalchemy.orm import relationship

from model import Base
from model.event_contestant import EventContestant
from model.location import Location


class Event(Base):
    __tablename__ = 'event'
    id = Column(Integer, primary_key=True)
    title = Column(String, nullable=False, unique=True)
    date = Column(Date, nullable=False)
    location_id = Column(Integer),
    longtitude = Column(Float, nullable=False)
    latitude = Column(Float, nullable=False)
    description = Column(String, nullable=False)
    difficulty = Column(Integer, nullable=False, default=3)
    creation_date = Column(Date, nullable=False, default=datetime.now)
    event_creator = Column(Integer, ForeignKey('users.id'), nullable=False)
    event_type = Column(String, nullable=False, default='Freestyle')

    # Relationships
    creator = relationship("User")
    contestants = relationship(EventContestant, back_populates="event")
    location = relationship('Location', foreign_key=location_id)

我从sqlalchemy获得的stactrace如下所示:

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|Location|location'. Original exception was: Could not determine join condition between parent/child tables on relationship Location.events - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

我真的很困惑,无法找出为什么这个一对多的方法应该起作用。

1 个答案:

答案 0 :(得分:2)

Event需要指向ForeignKey的{​​{1}}才能建立关系。具体来说,您想更改Location的定义以添加Event.location_id(并消除尾随逗号; ForeignKey('location.id')当前是一个元组)。