SqlAlchemy: create an object if it does not already exist?

I am 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 that it only adds an object if it does not already exist? That would be good...

 model.Session.create_if_does_not_exist(ev) 

Thanks!

+7
sqlalchemy
source share
2 answers

The standard template is as follows:

 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 very elegant (and I may have syntax errors - apologies), but does the job.

+3
source share

I found this recipe looking for a template to solve a similar problem that I have. I think this can be a good and clean, if not โ€œThe True Trueโ€ solution for what you were originally looking for.

+2
source share

All Articles