我试图在两个表之间创建关系:event和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')
以及事件.py看起来像这样:
^{pr2}$我从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.
我真的很困惑,也不明白为什么这种一对多应该有效。在
Event
需要一个指向Location
的ForeignKey
来构造关系。具体地说,您希望更改Event.location_id
的定义,以添加ForeignKey('location.id')
(并去掉后面的逗号;Event.location_id
当前是一个元组)。在相关问题 更多 >
编程相关推荐