Python SQLAlchemy - 什么是 declarative_base

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15175339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:32:43  来源:igfitidea点击:

SQLAlchemy - what is declarative_base

pythonsqlalchemy

提问by Aniruddha

I am learning sqlalchemy. Here is my initial code :

我正在学习 sqlalchemy。这是我的初始代码:

File : user.py

文件:user.py

from sqlalchemy import Column,Integer,Sequence, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
  __tablename__ = 'users'
  id = Column(Integer,Sequence('user_seq'),primary_key=True)
  username   = Column(String(50),unique=True)
  fullname = Column(String(150))
  password  = Column(String(50))
  def __init__(self,name,fullname,password):
    self.name = name
    self.fullname = fullname
    self.password = password

File main.py

文件main.py

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from user import User
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
if __name__ == '__main__':
  engine = create_engine('mysql://root:[email protected]:3306/test',echo=True)
  Base.metadata.create_all(engine, checkfirst=True)
  Session = sessionmaker(bind=engine)
  session = Session()
  ed_user = User('ed', 'Ed Jones', 'edspassword')
  session.add(ed_user)
  session.commit()

Now when I run main.py. It wont create table automatically & give me exception on 'session.commit()'. Now when I move line 'Base = declarative_base()' to different module & use same 'Base' variable in main.py & user.py. It create table.

现在当我运行 main.py 时。它不会自动创建表并在“session.commit()”上给我例外。现在,当我将“Base = declarative_base()”行移动到不同的模块并在 main.py 和 user.py 中使用相同的“Base”变量时。它创建表。

My question is what is 'declarative_base' ?

我的问题是什么是 'declarative_base' ?

采纳答案by Audrius Ka?ukauskas

declarative_base()is a factory function that constructs a base class for declarative class definitions (which is assigned to the Basevariable in your example). The one you created in user.py is associated with the Usermodel, while the other one (in main.py) is a different class and doesn't know anything about your models, that's why the Base.metadata.create_all()call didn't create the table. You need to import Basefrom user.py

declarative_base()是一个工厂函数,它为声明性类定义(Base在您的示例中分配给变量)构造基类。您在 user.py 中创建的一个与User模型相关联,而另一个(在 main.py 中)是一个不同的类并且对您的模型一无所知,这就是Base.metadata.create_all()调用没有创建表的原因。您需要Base从 user.py导入

from user import User, Base

instead of creating a new Baseclass in main.py.

而不是Base在 main.py中创建一个新类。