我有以下型号:
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
我为它编写了添加视图,非常基本:
employee = Employee()
form = Form(request, EmployeeSchema(), obj = employee)
if form.validate():
employee = form.bind(Employee())
try:
DBSession.add(employee)
DBSession.flush()
return HTTPFound(location = request.route_url('employees'))
except IntegrityError:
message = 'Oops!'
效果很好。但是UPDATE视图没有。我只是不保存。根据教程基本上使用相同的代码它应该工作。但事实并非如此,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 = ''
答案 0 :(得分:4)
您需要绑定到该项目,不需要添加新的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'))
就是这样。