简体   繁体   English

sqlalchemy:声明式基础如何导入自己的类

[英]sqlalchemy: declarative base how to import own classes

I am just starting with sqlalchemy orm. 我只是从sqlalchemy orm开始。 Basically, I am following the example from this tutorial . 基本上,我将遵循本教程中的示例。 While the code presented there works fine, my code ends in an error. 虽然此处显示的代码工作正常,但我的代码以错误结尾。

I have a script defining all declarations: 我有一个定义所有声明的脚本:

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)

This script runs without error. 该脚本运行无误。 But if I now want to insert something into my database with the following script... 但是,如果我现在想使用以下脚本将某些内容插入数据库中...

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()

...I get the following error: ...我收到以下错误:

from sqlalchemy_declarative import Creators, Base, Organizations
ImportError: cannot import name 'Creators'

I just cannot figure out where I have gone wrong. 我只是无法弄清楚哪里出了问题。 I'd appreciate any help. 我很感激任何帮助。 Thank you in advance. 先感谢您。

Oops. 哎呀。 Ok. 好。 I got it. 我知道了。 It really was a path/naming issue and nothing wrong with my code. 这确实是一个路径/命名问题,我的代码没有错。 Thanks @reptilicus for putting me on the right track. 感谢@reptilicus使我步入正轨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM