SQLAlchemy PostgreSQL金字塔更新问题

2024-04-26 23:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下型号:

class Employee (Base):
    __tablename__ = 'employees'

    id       = Column(Integer, primary_key=True, autoincrement=True)
    name     = Column(String(300), unique=True, nullable=False)
    phone_a  = Column(String(20), nullable=False)
    phone_b  = Column(String(20))
    email_a  = Column(String(400), nullable=False)
    email_b  = Column(String(400))
    address  = Column(String)
    charge   = Column(String(100), nullable=False)
    active   = Column(Boolean, default=True)

    created  = Column(DateTime, nullable=False, default=datetime.datetime.now)
    modified = Column(DateTime, onupdate=datetime.datetime.now)

    def __init__(self):
        self.active  = True
        self.created = datetime.datetime.now()

    def __unicode__(self):
        return self.name

我为它编写了添加视图,非常基本:

^{pr2}$

而且效果很好。但是更新视图没有,我只是不保存。根据教程基本上用相同的代码应该可以工作。但是没有,SQLAlchemy尝试插入一个新对象,而不是仅仅更新它。我试过了

import transaction
transaction.commit()

但没有成功。在

_id = request.matchdict['employeeid']
employee = DBSession.query(Employee).filter_by(id=_id).first()
form     = Form(request, EmployeeSchema(), obj = employee)

if form.validate():
    employee    = form.bind(Employee())
    try:
        DBSession.add(employee)
        return HTTPFound(location = request.route_url('employees'))
    except IntegrityError:
        message = ''

Tags: nameselfformidfalsetruedatetimestring
1条回答
网友
1楼 · 发布于 2024-04-26 23:36:27

您需要绑定到项目,您需要添加一个新的Employee()实例:

_id = request.matchdict['employeeid']
employee = DBSession.query(Employee).get(_id)
form     = Form(request, EmployeeSchema(), obj=employee)

if form.validate():
    form.bind(employee)
    return HTTPFound(location = request.route_url('employees'))

就这样。在

相关问题 更多 >