我刚刚开始使用sqlalchemy orm。基本上,我是关注this tutorial的例子。虽然那里提供的代码工作正常,但我的代码以错误结束。
我有一个定义所有声明的脚本:
import sqlalchemy as sql
import sqlalchemy.ext.declarative as sqldcl
import sqlalchemy.orm as sqlmap
engine = sql.create_engine('postgresql://username@localhost/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://username@localhost/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'
我无法弄清楚我哪里出错了。我很感激任何帮助。提前谢谢。
答案 0 :(得分:0)
糟糕。好。我知道了。它确实是一个路径/命名问题,我的代码没有任何问题。感谢@reptilicus让我走上正轨。