SQLAlchemy / PostGreSQL对外键属性的“无法适应类型”错误

时间:2010-10-28 12:14:56

标签: postgresql foreign-keys sqlalchemy

我遇到了PostGreSQL 8.4和表反射的问题。我的元数据对象似乎没问题(它有外键,主键,每个列和表)。但是当我尝试通过外键将一个对象与另一个对象关联时,我得到:“sqlalchemy.exc.ProgrammingError :( ProgrammingError)无法调整类型'EventParameters''INSERT INTO事件(”。

我正在使用SQLAlchemy 0.6.3(psycopg2 2.2.1)和PostGreSQL 8.4.5

在这里,我的代码:


#! /usr/bin/env python 

from sqlalchemy import MetaData, create_engine 
from sqlalchemy.orm import mapper, sessionmaker 

class EventParameters(object): 
    pass 

class Event(object): 
    pass 

engine = create_engine('postgresql://postgres:toto@127.0.0.1:5432/renass') 
metadata = MetaData() 
metadata.reflect(bind=engine) 
Session = sessionmaker(bind=engine) 
session = Session() 
mapper(EventParameters, metadata.tables['eventparameters']) 
mapper(Event, metadata.tables['event']) 

ep = EventParameters() 
ep.publicid = 'test' 

e = Event() 
e.publicid = 'test' 
e.eventparametersid=ep 

session.add(e) 
session.commit()

和我的数据库:


CREATE TABLE EventParameters ( 
    id SERIAL PRIMARY KEY, 
    publicID varchar(255) UNIQUE NOT NULL, 
    description varchar(255), 
    creationInfo_agencyID varchar(64), 
    creationInfo_agencyURI varchar(255), 
    creationInfo_author varchar(128), 
    creationInfo_authorURI varchar(255), 
    creationInfo_creationTime time, 
    creationInfo_version varchar(64) 
); 

CREATE TABLE Event ( 
    id SERIAL PRIMARY KEY, 
    eventParametersID integer NOT NULL REFERENCES EventParameters(id), 
    publicID varchar(255) UNIQUE NOT NULL, 
    preferredOriginID integer, 
    preferredMagnitudeID integer, 
    preferredFocalMechanismID integer, 
    type EventType, 
    typeCertainty EventTypeCertainty, 
    creationInfo_agencyID varchar(64), 
    creationInfo_agencyURI varchar(255), 
    creationInfo_author varchar(128), 
    creationInfo_authorURI varchar(255), 
    creationInfo_creationTime time, 
    creationInfo_version varchar(64) 
);

似乎SQLAlchemy不将属性“eventparametersid”识别为关系......

提前谢谢你 法比安

1 个答案:

答案 0 :(得分:1)

要使代码正常工作,您应该更改Event类的映射器调用,以包含两个类之间的映射

mapper(Event, metadata.tables['event'], properties={
    'eventparameters': relation(EventParameters)
})

然后使用该列分配EventParameters实例

ep = EventParameters()
ep.publicid = 'test'

e = Event()
e.publicid = 'test'
e.eventparameters = ep