SQLALCHEMY Fügen Sie einer automatisierten Basis -Ergebnissen eine Tabelle hinzu, die in "Objekt kein Attribut" _sa_instPython

Python-Programme
Anonymous
 SQLALCHEMY Fügen Sie einer automatisierten Basis -Ergebnissen eine Tabelle hinzu, die in "Objekt kein Attribut" _sa_inst

Post by Anonymous »

Ich spiegele eine Remote -MS -SQL zu einem lokalen SQLite DB.

Code: Select all

eng_str = rf"mssql+pymssql://{user_domain}\{username}:{password}@{hostip}/{dbname}"
engine_remote = create_engine(eng_str, echo=False)

dbfp = Path("../../data/mydb.sqlite3")
engine_local = create_engine(f"sqlite:///{dbfp}", echo=False)

Base = automap_base()

# See ORM documentation on intercepting column definitions: https://docs.sqlalchemy.org/en/20/orm/extensions/automap.html#intercepting-column-definitions
@event.listens_for(Base.metadata, "column_reflect")
def genericize_datatypes(inspector, tablename, column_dict):
# Convert dialect specific column types to SQLAlchemy agnostic types
# See: https://stackoverflow.com/questions/79496414/convert-tinyint-to-int-when-mirroring-microsoft-sql-server-to-local-sqlite-with
# See Core documentation on reflecting with database-agnostic types: https://docs.sqlalchemy.org/en/20/core/reflection.html#reflecting-with-database-agnostic-types
old_type = column_dict['type']
column_dict["type"] = column_dict["type"].as_generic()
# We have to remove collation when mirroring a Microsoft SQL server into SQLite
# See: https://stackoverflow.com/a/59328211/1719931
if getattr(column_dict["type"], "collation", None) is not None:
column_dict["type"].collation = None

# Load Base with remote DB metadata
Base.prepare(autoload_with=engine_remote)
< /code>
Ich muss jedoch meiner DB eine Tabelle hinzufügen, also habe ich: < /p>
getanclass MissingApl(Base):
__tablename__ = "missing_apl"
id: Mapped[int] = Column(Integer, primary_key=True)
appln_nr: Mapped[int] = Column(Integer)
< /code>
Und dann erstelle ich die Metadaten auf dem lokalen DB: < /p>
Base.metadata.create_all(engine_local)
< /code>
jedoch beispielsweise: < /p>
testobj=MissingApl(appln_nr=9999)
print(testobj)
with Session(engine_local) as session:
session.add(testobj)
session.commit()
< /code>
führt zu: < /p>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File \Python\Python313\Lib\site-packages\sqlalchemy\orm\session.py:3477, in Session.add(self, instance, _warn)
3476 try:
-> 3477     state = attributes.instance_state(instance)
3478 except exc.NO_STATE as err:

AttributeError: 'MissingApl' object has no attribute '_sa_instance_state'

The above exception was the direct cause of the following exception:

UnmappedInstanceError                     Traceback (most recent call last)
Cell In[26], line 4
2 print(testobj)
3 with Session(engine_local) as session:
----> 4     session.add(testobj)
5     session.commit()

File \Python\Python313\Lib\site-packages\sqlalchemy\orm\session.py:3479, in Session.add(self, instance, _warn)
3477     state = attributes.instance_state(instance)
3478 except exc.NO_STATE as err:
-> 3479     raise exc.UnmappedInstanceError(instance) from err
3481 self._save_or_update_state(state)

UnmappedInstanceError: Class '__main__.MissingApl' is not mapped
Warum gibt es mir diesen Fehler und wie kann ich ihn beheben?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post