Handling unique constraints

3 views
Skip to first unread message

Matt Haggard

unread,
Jan 4, 2008, 3:06:11 PM1/4/08
to sqlalchemy
I'm using SQLAlchemy with Pylons and am having trouble validating
data. I have an App object mapped to a table with a unique constraint
on App.number.

Here's some code:

q = Session.query(App)
if app_id:
q = q.filter_by(id=app_id).first()
if q:
c.app = q
number = request.params.get('number')
notes = request.params.get('notes')
if appmodel and number:
try:
q.number = number
q.notes = notes
Session.save(q)
Session.commit()
c.message = 'Record updated'
except:
# restore pre-form data ?? how??
c.message = 'Error updating record'
return render('index.mtl')
else:
return self.index()

My questions are:

1) When I do the try statement, the value of q.number changes to
whatever the user passed in via the form -- even if it's invalid, so
that when I render the page, the invalid value is used. How do I
reset the object to have the values it had before I did the try? Do I
have to get it afresh from the db?

2) How do I let the user know which value caused the record not to
update? What information does SQLAlchemy provide back that I can use
to say: "You're number must be unique... and such-and-such must be
greater than 0, etc..?"

Thanks,

Matt Haggard

sdo...@sistechnology.com

unread,
Jan 5, 2008, 1:13:09 AM1/5/08
to sqlal...@googlegroups.com
try something like session.refresh( obj) or similar

> 2) How do I let the user know which value caused the record not to
> update? What information does SQLAlchemy provide back that I can use
> to say: "You're number must be unique... and such-and-such must be
> greater than 0, etc..?"

mmh, do not mistake DB-constraints with validation-rules.
the only sensible info u can get here is that the record is not unique
(check what sort of exception that throws), but any further interpretation -
why, what, where - is up to you - u have to know what field u have just
set/changed, etc.

Chris

unread,
Jan 6, 2008, 12:16:06 AM1/6/08
to sqlalchemy
Matt,
Take a look at the formencode module, it will simplify what you are
trying to do here - handles all your parameter validation, form
filling, and telling the user X,Y,Z are wrong etc.

http://wiki.pylonshq.com/display/pylonsdocs/Form+Handling

and formencode docs

http://www.formencode.org/
Reply all
Reply to author
Forward
0 new messages