2011-09-29 2 views
1

사용자의 모든 사용자 ID를 변경할 수 있도록 데이터베이스에서 100 개가 넘는 테이블을로드하는 프로그램을 만들려고합니다.SQLAlchemy : 목록에서 동적으로 테이블로드

모든 테이블을 개별적으로 매핑하는 대신 객체 배열을 사용하여 각 테이블을 매핑하는 루프를 사용하기로 결정했습니다. 이렇게하면 테이블 정의를 구성 파일에 저장하고 나중에 업데이트 할 수 있습니다.

def init_model(engine): 
    """Call me before using any of the tables or classes in the model""" 
    meta.Session.configure(bind=engine) 
    meta.engine = engine 

class Table: 
    tableID = '' 
    primaryKey = '' 
    pkType = sa.types.String() 
    class mappedClass(object): 
     pass 


WIW_TBL = Table() 
LOCATIONS_TBL = Table() 

WIW_TBL.tableID = "wiw_tbl" 
WIW_TBL.primaryKey = "PORTAL_USERID" 
WIW_TBL.pkType = sa.types.String() 

LOCATIONS_TBL.tableID = "locations_tbl" 
LOCATIONS_TBL.primaryKey = "LOCATION_CODE" 
LOCATIONS_TBL.pkType = sa.types.Integer() 

tableList = ([WIW_TBL, LOCATIONS_TBL]) 

for i in tableList: 

    i.tableID = sa.Table(i.tableID.upper(), meta.metadata, 
    sa.Column(i.primaryKey, i.pkType, primary_key=True), 
    autoload=True, 
    autoload_with=engine) 

    orm.mapper(i.mappedClass, i.tableID) 

이 코드는 반환 된 오류는 다음과 같습니다 : 여기

지금까지 내 코드입니다

sqlalchemy.exc.ArgumentError: Class '<class 'changeofname.model.mappedClass'>' already has a primary mapper defined. Use non_primary=True to create a non primary Mapper. clear_mappers() will remove *all* current mappers from all classes. 

는 모든 클래스를 쳐하고 ENTITY_NAME 방식은 '아무튼 나는이 clear_mappers를 사용하지 못할 여기에 적용되는 것처럼 보입니다.

모든 개체는 동일한 클래스를 사용하려고하지만 모든 개체는 고유 한 인스턴스를 가져야합니다.

누구에게 아이디어가 있습니까?

답변

1

글쎄, 귀하의 경우에는 * 입니다. 동일 Class에 매핑하면 다른 Table에 매핑하려고합니다.

class Table(object): 
    tableID = '' 
    primaryKey = '' 
    pkType = sa.types.String() 
    def __init__(self): 
     self.mappedClass = type('TempClass', (object,), {}) 

을하지만 약간 청소기 버전을 선호하는 것 :이 문제를 해결하려면 각 Table 동적으로 클래스를 생성

class Table2(object): 
    def __init__(self, table_id, pk_name, pk_type): 
     self.tableID = table_id 
     self.primaryKey = pk_name 
     self.pkType = pk_type 
     self.mappedClass = type('Class_' + self.tableID, (object,), {}) 
# ... 
WIW_TBL = Table2("wiw_tbl", "PORTAL_USERID", sa.types.String()) 
LOCATIONS_TBL = Table2("locations_tbl", "LOCATION_CODE", sa.types.Integer()) 
+0

완벽한, 내가 필요 정확히 이잖아! 나는 이전에 type()을 시도했지만 성공하지 못했습니다. 고마워, 대단히 감사합니다! 어떤 이유로 그것이 뷰로 전달되지 않지만, 그것을 이해할 수 없습니다 : D – JackalopeZero

+0

클래스를 가져올 때 볼 수있게하려면, 그들을 globals()에 추가해야합니다. 예를 들면 다음과 같습니다 :'self.mappedClass = type ('Class_'+ self.tableID, (object,), {}) '행 다음에'globals() [ 'Class_'+ self.tableID] = self.mappedClass' 행을 추가하십시오. . 이 경우 뷰는'Class_locations_tbl' 및'Class_wiw_tbl' 클래스를 가져올 수 있습니다. – van

관련 문제