модели
# model1.py # coding: utf-8 from sqlalchemy import Column, INTEGER, String, DATETIME, FLOAT, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship BASE = declarative_base() class Model1(BASE): __tablename__ = 'model1' id = Column(INTEGER, primary_key=True, nullable=False) model2_ids = relationship('Model2')
# model2.py # coding: utf-8 from sqlalchemy import Column, INTEGER, String, DATETIME from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship BASE = declarative_base() class Model2(BASE): __tablename__ = 'model2' id = Column(INTEGER, primary_key=True, nullable=False) model1_id = Column(INTEGER, ForeignKey('model1.id'))
модели лежат в БД, заливал через миграции sqlalchemy-migrate
# coding: utf-8 from sqlalchemy import MetaData, String, Table, Column, INTEGER, FLOAT, DATETIME from migrate.changeset.constraint import ForeignKeyConstraint meta = MetaData() table1 = Table( 'model1', meta, Column('id', INTEGER, primary_key=True, nullable=False), mysql_charset='utf8' ) table2 = Table( 'model2', meta, Column('id', INTEGER, primary_key=True, nullable=False), Column('model1_id', INTEGER), mysql_charset='utf8' ) fkey = ForeignKeyConstraint( columns=[table2.c.model1_ids], refcolumns=[table1.c.id] ) def upgrade(migrate_engine): meta.bind = migrate_engine table1.create() table2.create() fkey.create() def downgrade(migrate_engine): meta.bind = migrate_engine table1.drop() table1.drop() fkey.drop()
Вопросы:
1.
model2_ids = relationship('Model2')
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|VMInstance|vminstance, expression 'Model2' failed to locate a name ("name 'Model2' is not defined"). If this is a class name, consider adding this relationship() to the <class '...'> class after both dependent classes have been defined.
2. ок. сделал явный импорт, и подсунул ему сам класс
model2_ids = relationship(Model2)
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'model2.model1_ids' could not find table 'model1' with which to generate a foreign key to target column 'id'
объясните пожалуйста, что я делаю не так? я чет запутался
БД мускул. в мускуле таблицы есть.