使用SqlAlchemy ORM更新行

10

我正试图从数据库中获取一行数据,修改该行并将其再次保存。
使用SqlAlchemy实现所有操作。

我的代码:

from sqlalchemy import Column, DateTime, Integer, String, Table, MetaData
from sqlalchemy.orm import mapper
from sqlalchemy import create_engine, orm

metadata = MetaData()

product = Table('product', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(1024), nullable=False, unique=True),

)

class Product(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

mapper(Product, product)


db = create_engine('sqlite:////' + db_path)
sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
session = orm.scoped_session(sm)

result = session.execute("select * from product where id = :id", {'id': 1}, mapper=Product)
prod = result.fetchone() #there are many products in db so query is ok

prod.name = 'test' #<- here I got AttributeError: 'RowProxy' object has no attribute 'name'

session .add(prod)
session .flush()

很不幸,这样做不起作用,因为我试图修改RowProxy对象。在SqlAlchemy ORM中,如何以想要的方式(加载、更改和保存/更新行)操作?


1
快速浏览提示:您不会将对象添加到会话以进行修改。您是在创建新行时添加的。通常,您只需修改代理对象,然后在会话对象上提交即可。此外,如果您真的想使用ORM,则通常不会在SQL中构造查询并使用execute方法。请使用查询生成器。 - Keith
他说在修改RowProxy对象时遇到了AttributeError。你为什么会期望那样能够工作呢? - Terrence Brannon
1个回答

14

我认为你的意图是使用对象关系API。因此,要更新数据库中的行,您需要通过从表记录加载映射对象并更新对象的属性来执行此操作。

请参见下面的代码示例。 请注意,我已添加了用于创建新映射对象和创建表中第一条记录的示例代码,同时在最后还有被注释掉的代码以删除该记录。

from sqlalchemy import Column, DateTime, Integer, String, Table, MetaData
from sqlalchemy.orm import mapper
from sqlalchemy import create_engine, orm

metadata = MetaData()

product = Table('product', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(1024), nullable=False, unique=True),

)

class Product(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __repr__(self):
        return "%s(%r,%r)" % (self.__class__.name,self.id,self.name)

mapper(Product, product)


db = create_engine('sqlite:////temp/test123.db')
metadata.create_all(db)

sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
session = orm.scoped_session(sm)

#create new Product record:
if session.query(Product).filter(Product.id==1).count()==0:

    new_prod = Product("1","Product1")
    print "Creating new product: %r" % new_prod
    session.add(new_prod)
    session.flush()
else:
    print "product with id 1 already exists: %r" % session.query(Product).filter(Product.id==1).one()

print "loading Product with id=1"
prod = session.query(Product).filter(Product.id==1).one()
print "current name: %s" % prod.name
prod.name = "new name"

print prod


prod.name = 'test'

session.add(prod)
session.flush()

print prod

#session.delete(prod)
#session.flush()

PS:SQLAlchemy 还提供了 SQL 表达式 API,允许直接使用表记录而不创建映射对象。在我的实践中,我们在大多数应用程序中使用对象关系 API,有时需要高效地执行低级别的数据库操作,例如使用 SQL 表达式 API 以一次查询插入或更新数千条记录。

SQLAlchemy 文档的直接链接:


只能使用ORM吗?还是也可以使用SQLAlchemy表达式语言? - Carolyn Conway

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接