1
我剛剛開始使用sqlalchemy orm。基本上,我遵循this tutorial的示例。雖然在那裏提供的代碼工作正常,但我的代碼以錯誤結尾。sqlalchemy:聲明性基礎如何導入自己的類
我定義所有聲明的腳本:
import sqlalchemy as sql
import sqlalchemy.ext.declarative as sqldcl
import sqlalchemy.orm as sqlmap
engine = sql.create_engine('postgresql://[email protected]/dbname')
Base = sqldcl.declarative_base(metadata=sql.MetaData(engine, schema='schemaname'))
class Creators(Base):
__tablename__ = 'creators'
id = sql.Column(sql.Integer, primary_key=True)
entity1 = sql.Column(sql.Integer)
entity2 = sql.Column(sql.Unicode())
class Organizations(Base):
__tablename__ = 'organizations'
id = sql.Column(sql.Integer, primary_key=True)
fk_creators = sql.Column(sql.Integer, sql.ForeignKey('creators.id'))
creators = sqlmap.relationship(Creators)
entity4 = sql.Column(sql.Integer)
entity5 = sql.Column(sql.Unicode())
Base.metadata.create_all(engine)
該腳本運行沒有錯誤。但是,如果我現在要插入一些內容我用下面的腳本,數據庫......
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Creators, Base, Organizations
engine = create_engine('postgresql://[email protected]/dbname')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
new_creator = Creators(entity1='111')
session.add(new_creator)
session.commit()
new_organization = Organizations(entity4='111', entity5='Blabla', creators=new_creator)
session.add(new_organization)
session.commit()
...我收到以下錯誤:
from sqlalchemy_declarative import Creators, Base, Organizations
ImportError: cannot import name 'Creators'
我只是想不通,我已經走了錯誤。我會很感激任何幫助。先謝謝你。
這只是一個路徑問題,請確保該文件在您的Python路徑中 – reptilicus