簡體   English   中英

SQLAlchemy 多態性:創建子記錄時父表不存在

[英]SQLAlchemy Polymorphism: Parent table does not exist when creating a child record

嘗試提交記錄時會出現以下異常:

OperationalError (sqlite3.OperationalError) no such
table: basedocument [SQL: INSERT INTO basedocument (common_field,
doc_type) VALUES (?, ?)] [parameters: ('humanidade', 'user')]

basedocument是多態關聯中的父表, user是子表。

在子表上創建記錄時不應該創建父表嗎?

這是代碼:

from sqlalchemy import create_engine, ForeignKey, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine("sqlite:///temp.db")
sessao = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()


class BaseDocument(Base):
    __tablename__ = "basedocument"
    id = Column(Integer, primary_key=True)
    common_field = Column(String)
    doc_type = Column(String(20))
    __mapper_args__ = {
        "polymorphic_identity": "basedocument",
        "polymorphic_on": doc_type,
    }


class User(BaseDocument):
    __tablename__ = "user"
    id = Column(Integer, ForeignKey("basedocument.id"), primary_key=True)
    name = Column(String)
    fullname = Column(String)
    nickname = Column(String)
    __mapper_args__ = {
        "polymorphic_identity": "user",
    }


u1 = User(
    name="Dumont",
    fullname="Santos Dumont",
    nickname="voador",
    common_field="humanidade",
)
sessao.add(u1)
sessao.commit()
print("\nObject:  ", u1)

好吧,我只是注意到我忘了使用

Base.metadata.create_all(engine)

在類定義之后。 這才是真正創建表格的原因。

此答案對圍繞“沒有此類表”錯誤的許多問題有效。

正確的代碼:

from sqlalchemy import create_engine, ForeignKey, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine("sqlite:///temp.db")
sessao = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()


class BaseDocument(Base):
    __tablename__ = "basedocument"
    id = Column(Integer, primary_key=True)
    common_field = Column(String)
    doc_type = Column(String(20))
    __mapper_args__ = {
        "polymorphic_identity": "basedocument",
        "polymorphic_on": doc_type,
    }


class User(BaseDocument):
    __tablename__ = "user"
    id = Column(Integer, ForeignKey("basedocument.id"), primary_key=True)
    name = Column(String)
    fullname = Column(String)
    nickname = Column(String)
    __mapper_args__ = {
        "polymorphic_identity": "user",
    }


Base.metadata.create_all(engine)

u1 = User(
    name="Dumont",
    fullname="Santos Dumont",
    nickname="voador",
    common_field="humanidade",
)
sessao.add(u1)
sessao.commit()
print("\nObject:  ", u1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM