SQLAlchemy关系映射错误

时间:2016-06-16 18:11:47

标签: python database sqlite sqlalchemy

我正在编写一个程序来记录我的植物的过程和种子的种植日期。所有数据都可以通过REST-Api进行调整,但最后一次数据库迁移会让我感到厌烦。我想保存有关种植种子的数据(api.database.plantevent.py):

class Plantevent(BaseTable):
"""
The database model for a planting event when seeds are planted.
"""
    __tablename__ = 'plantevents'

    plantdate = Column(Date, nullable=False)
    seed_id = Column(Integer, ForeignKey('seeds.id'), nullable=False)
    amount = Column(Integer, nullable=False)  # number of planted seeds
    sprouted = Column(Integer)  # number of sprouted seeds
    soaked = Column(Boolean)  
    first_seedling = Column(Date)  # Date of the first seedling
    plants = relationship("Plant", backref='plantevent')

" BaseTable"是一个抽象表,只包含id字段。

如果种子发芽,我想得到" plantevent"的所有植物。通过"植物"关系。这是工厂的模型(api.database.plant.py):

class Plant(BaseTable):
"""
The database model for plants.
"""
    __tablename__ = 'plants'

    name = Column(String(255), nullable=False)
    crop_yield = Column(Integer)
    plantevent_id = Column(Integer, ForeignKey('plantevents.id'))

一切都很有效,除了"植物" - 关系" Plantevent"我无法弄清楚原因。如果我对" plant" -relationship发表评论,一切都会好的。 为了完整性,这里是生成的sqlite-database的模式:

CREATE TABLE plantevents (
  id INTEGER NOT NULL, 
  plantdate DATE NOT NULL, 
  seed_id INTEGER NOT NULL, 
  amount INTEGER NOT NULL, 
  sprouted INTEGER, 
  soaked BOOLEAN, 
  first_seedling DATE, 
  PRIMARY KEY (id), 
  FOREIGN KEY(seed_id) REFERENCES seeds (id), 
  CHECK (soaked IN (0, 1))
);
CREATE TABLE plants (
  id INTEGER NOT NULL, 
  name VARCHAR(255) NOT NULL, 
  crop_yield INTEGER, 
  plantevent_id INTEGER, 
  PRIMARY KEY (id), 
  FOREIGN KEY(plantevent_id) REFERENCES plantevents (id)
);

我得到的错误,如果我尝试获得一个计划事件,请执行以下操作:

sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Plantevent|plantevents, expression 'Plant' failed to locate a name ("name 'Plant' is not defined"). If this is a class name, consider adding this relationship() to the <class 'api.database.plantevent.Plantevent'> class after both dependent classes have been defined.

有谁知道我为什么会收到此错误?我把它与db-model中的其他关系进行了比较,但我看不出有任何区别。

编辑: 这是BaseTable的模型(api.database。 init .py):

class BaseTable(Base):
    """
    Abstract base table which provides the id field for each table
    """
    __abstract__ = True

    id = Column(Integer, primary_key=True)

0 个答案:

没有答案