SeanPlusPlus
SeanPlusPlus

Reputation: 9033

does sqlalchemy have an equivalent to datamapper's first_or_create method?

using datamapper, if you want to "either find the first resource matching some given criteria or just create that resource if it can't be found, you can use #first_or_create."

i am using flask-sqlalchemy and am wondering if there is a similar feature.

thanks!

Upvotes: 1

Views: 1158

Answers (1)

Mohammad Efazati
Mohammad Efazati

Reputation: 4910

there is some things in django named get_or_create you can create somethings like that for sqlalachemy

def get_or_create(session, model, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
    else:
        instance = model(**kwargs)
        return instance

from here: python - Does SQLAlchemy have an equivalent of Django's get_or_create? - Stack Overflow -> Does SQLAlchemy have an equivalent of Django's get_or_create?

Upvotes: 1

Related Questions