python - 在 SqlAlchemy ORM 中更新行

标签 python sqlalchemy

我正在尝试从数据库中获取一行,修改该行并再次保存。
一切都通过使用 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 方式做我想做的事(加载、更改和保存(更新)行)?

最佳答案

我假设您的意图是使用 Object-Relational 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 Expression API这允许直接使用表记录而不创建映射对象。在我的实践中,我们在大多数应用程序中使用 Object-Relation API,有时当我们需要高效执行低级数据库操作(例如使用一个查询插入或更新数千条记录)时,我们使用 SQL 表达式 API。

SQLAlchemy 文档的直接链接:

关于python - 在 SqlAlchemy ORM 中更新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14307238/

相关文章:

python - 删除 sqlalchemy 中多对多辅助表关联中的所有内容

postgresql - 如何创建从子查询返回数组的查询?

python - 如何根据 pandas python 中的特定列合并两个数据框?

python - 在 Python 中从 txt 文件创建新的 sqlite 数据库表

python - Postgres/psycopg2 - 插入字符串数组

python - SQLAlchemy 会清理原始 SQL 吗?

sql-server - 在 MS SQL Server 上使用 sqlalchemy 定义一个 varbinary(max) 列

python - 是否可以像在 GUI 中一样通过 Excel 公式填写整个列? #gspread

python - 保存在 python 中使用 peek() 显示的图像

sqlalchemy - 如何处理 Pyramid 中的模型变化