Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to insert an object with a foreign key in SQLAlchemy?

When using SQLAlchemy, what is the ideal way to insert an object into a table with a column that is a foreign key and then commit it? Is there anything wrong with inserting objects with a foreign in the code below?

def retrieve_objects():
    session = DBSession()
    return session.query(SomeClass).all()

def insert_objects():
    session = DBSession()
    for obj in retrieve_objects():
        another_obj = AnotherClass(somefield=0)
        obj.someforeignkey = another_obj
        session.add(obj)
    session.flush()
    transaction.commit()
    session.close()
    return None
like image 650
Mark Tomlin Avatar asked Apr 10 '11 08:04

Mark Tomlin


1 Answers

If you aren't using SQLAlchemy relationships on your ORM objects you have to manually deal with foreign keys. This means you have to create the parent object first, get its primary key back from the database, and use that key in the child's foreign key:

def retrieve_objects():
    session = DBSession()
    return session.query(SomeClass).all()

def insert_objects():
    session = DBSession()
    for obj in retrieve_objects():
        another_obj = AnotherClass(somefield=0)
        session.add(another_obj)
        session.flush() # generates the pkey for 'another_obj'
        obj.someforeignkey = another_obj.id # where id is the pkey
        session.add(obj)
    transaction.commit()
like image 160
Michael Merickel Avatar answered Sep 26 '22 03:09

Michael Merickel