다양한 선택 기준에 따라 원래 테이블의 하위 집합 인 sqllite 테이블에서 tmp 테이블을 만들었습니다. 스크린 샷에 샘플이 있습니다.
각 필드를 업데이트하기 위해 테이블 레코드를 한 번에 하나씩 반복하려고합니다. 매퍼에 설명 된 문제가 발생 하여 기본 키 열을 어셈블 할 수 없습니다 . http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key 의 권장 사항을 기반으로합니다 . 이 토론을 기반으로 고유 한 ID 인 'id'열인 후보 키가 있습니다. 따라서 코드를 다음과 같이 변경했습니다.
source_table= self.source
engine = create_engine(db_path)
Base = declarative_base()
# metadata = Base.metadata
# Look up the existing tables from database
Base.metadata.reflect(engine)
# Create class that maps via ORM to the database table
table = type(source_table, (Base,), {'__tablename__': source_table}, __mapper_args__ = {
'primary_key':'id'
})
Session = sessionmaker(bind=engine)
session = Session()
i = 0
for row in session.query(table).limit(500):
i += 1
print object_as_dict(row)
그러나 이것은 다음을 제공합니다.
TypeError: type() takes 1 or 3 arguments
id를 기본 키로 식별하기 위해 mapper_args 인수를 어떻게 사용할 수 있습니까?
편집하다:
나는 시도했다 :
table = type(source_table, (Base,), {'__tablename__': source_table}, {"__mapper_args__": {"primary_key": [Base.metadata.tables[source_table].c.id]}})
기부:
TypeError: type() takes 1 or 3 arguments
__mapper_args__
클래스에 정의 된 속성이어야합니다. 작성해야하는 반면
class Foo(Base):
...
__mapper_args__ = {...}
class
구문 으로 클래스를 정의 할 때 다음과 같이 작성해야합니다.
type("Foo", (Base,), {..., "__mapper_args__": {...}})
type
함수 로 클래스를 정의 할 때 .
참고 __mapper_args__
해야 할 수도 있습니다
{"primary_key": [Base.metadata.tables[source_table].c.id]}
대신에
{"primary_key": "id"}
제대로 작동합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다