使用文件数据初始化SQLAlchemy表:空对象

时间:2015-04-27 22:23:06

标签: python-3.x sqlalchemy

我刚开始使用SQLAlchemy在PostgreSQL中创建表格,我真的会在这里得到经验丰富的人的帮助:

我在使用从文件读取的数据初始化表时遇到问题。这是我尝试过的一个例子,部分基于this post

schema = "spectr" # schema exists in the database
connstr = "postgresql+psycopg2://postgres:postgres@localhost/postgres"
mymetadata = MetaData(schema=schema)
Base = declarative_base(metadata=mymetadata)
engine = create_engine(connstr, echo=True)

class File(Base):
""" File metadata """
__tablename__ = "files"
id = Column(Integer, primary_key=True)
altitude = Column(Numeric(precision=6, scale=1))
average_ref = Column(Integer, nullable=False)
average_target = Column(Integer, nullable=False)

def __init__(self, filename=None):
    if filename != None:
        dic = read_sed(filename)

        for k in File.__table__.columns.keys():
            if k != 'id':
                File.k = dic.get(k, None)

# 'read_sed' is a function that returns a dictionary of the data in filename

File().__table__.create(engine, checkfirst=True)
file = File(filename)

Session = sessionmaker(bind=engine)
session = Session()
session.add(file)
session.commit()

# This is the point where I get an error since file is empty and many columns are nullable=False. 

这里是错误输出的结束:

sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "average_ref" violates not-null constraint
DETAIL:  Failing row contains (1, null, null, null).
[SQL: 'INSERT INTO spectro.files (altitude, average_ref, average_target)  VALUES (%(altitude)s, %(average_ref)s, %(average_target)s) RETURNING spectro.files.id'] [parameters: {'average_target': None, 'average_ref': None, 'altitude': None}]

知道我做错了吗?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我不确定这条线应该做什么:

File.k = dic.get(k, None)

从外观上看,它会将属性k(不是变量k的值)设置为File类(不是实例)。假设您要在当前File实例的加载文件中设置高度,average_ref,average_target等字段,您可能应该使用selfsetattr上设置它们:

setattr(self, k, dic.get(k, None))

如果dicdict的实例,则, None是多余的,您只能使用setattr(self, k, dic.get(k))