Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy: create object if does not exist already?

Tags:

sqlalchemy

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!

like image 308
AP257 Avatar asked Aug 16 '10 11:08

AP257


2 Answers

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).count()
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.

like image 152
Alex Wilson Avatar answered Nov 02 '22 20:11

Alex Wilson


I've found this recipe while looking for a pattern to solve a similar problem I have. I think this might be a nice and clean if not 'The One True' solution to what you were originally looking for.

like image 35
jhnwsk Avatar answered Nov 02 '22 19:11

jhnwsk