tags:

views:

82

answers:

1

I'm new to SQLAlchemy. I currently have:

ev = model.EnumerationValue(key=key_level_2, code=level_2)
ev.keyvalues[key_parent] = level_1
model.Session.add(ev)

How can I change this so it only adds the object if it doesn't already exist? This would be nice...

model.Session.create_if_does_not_exist(ev)

Thanks!

A: 

The standard pattern would appear to be:

ev = model.Session.query(model.EnumerationValue).filter(model.EnumerationValue.key==key_level_2).filter(model.EnumerationValue.code==level_2)
if not ev:
    ev = model.EnumerationValue(key=key_level_2, code=level_2)
    ev.keyvalues[key_parent] = level_1
    model.Session.add(ev)

Not terribly elegant (and I may have syntax errors - apologies) but does the job.

Alex