0

我想使用关系将对象添加到数据库中,代码很糟糕:

代码在eclipse中运行,数据库是postgresql

from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, String, Sequence
from sqlalchemy.orm import mapper, relationship, backref
from sqlalchemy.engine import create_engine
from sqlalchemy.orm.session import sessionmaker

创建引擎和会话

engine = create_engine("postgresql+psycopg2://openpg:openpgpwd@localhost:5432/testdb", echo=True)
Session = sessionmaker(bind = engine)
session = Session()
metadata = MetaData()

创建用户和地址类

user = Table('user', metadata,
             Column('id',Integer,Sequence('user_id_seq'),primary_key=True),
             Column('name',String(50)),
             Column('fullname',String(50)),
             Column('password',String(12)))

class User(object):
    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

address = Table('address', metadata,
                Column('id', Integer,Sequence('address_id_seq'),primary_key=True),
                Column('user_id',Integer,ForeignKey('user.id')),
                Column('email_address',String(50)))

class Address(object):
    def __init__(self, user_id, email_address):
        self.user_id = user_id
        self.email_address = email_address

mapper(User,user,properties = {'addresses': relationship(Address, backref=backref('user',order_by=address.c.id))})        
mapper(Address, address)

if __name__ == '__main__':
    jack = User('jack', 'Jack Bean', 'gjffdd')
    jack.addresses = [Address(email_address='jack@google.com'),Address  (email_address='jack@yahoo.com')]
    session.add(jack)
    session.commit()

在eclipse中运行,结果是:

 Traceback (most recent call last):
  File "D:\workspace\test1\dbtest\testrelationship.py", line 68, in <module>
    jack.addresses = [Address(email_address='jack@google.com'),Address   (email_address='jack@yahoo.com')]
TypeError: __init__() takes exactly 3 arguments (2 given)

不知道怎么解决,谢谢!

4

1 回答 1

0

您没有user_idAddress.__init__. 所以摆脱它:

class Address(object):
    def __init__(self, email_address):
        self.email_address = email_address

无论如何,SA 都会负责在数据库中存储正确的值。

于 2013-04-28T11:06:24.350 回答