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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With