Demo entry 2296987

sincere get_or_crete

   

Submitted by anonymous on Jul 21, 2015 at 13:31
Language: Python. Code size: 1.1 kB.

def really_unsafe_get_or_create(session, model_, defaults=None, i_agree_to_create_a_unique_constraint_in_database=False, **kwargs):
    """
    SQLAlchemy's implementation of Django's get_or_create method, but with better warnings.
    Make sure you create a unique index in the database with all fields used as kwargs.
    I'm serious, you'd better do it!
    """

    if not i_agree_to_create_a_unique_constraint_in_database:
        raise ScrewYou('Ask to quit! Ask to quit!')

    query = session.query(model_).filter_by(**kwargs)
    record_count = query.count()

    if record_count > 1:
        raise MultipleRecordsFound('When I say "create a unique index", I mean it!')
    elif record_count == 1:
        return query.first()

    model_kwargs = {}
    if isinstance(defaults, dict):
        model_kwargs.update(defaults)
    model_kwargs.update(kwargs)

    instance = model_(**model_kwargs)
    session.add(instance)

    try:
        session.commit()
        return instance
    except IntegrityError:
        return query.first()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).