简体   繁体   中英

SQLAlchemy: How to handle adjacency list with foreign key to other table?

Let us consider the following minimal example:

  • measurement table with an id and a name.
  • simulation table with an id and a name. Additionaly there is a foreign key referencing the id of the measurement the simulation is based on and a foreign key referencing an other simulation the simulation is based on.

A minimal working example of the code I came up with is the following:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import sessionmaker, scoped_session, relationship

engine = create_engine('postgresql://postgres:12345@localhost:5432/Example')

Session = scoped_session(sessionmaker(bind=engine))

Base = declarative_base()

class Measurement(Base):
    __tablename__ = 'measurement'

    id = Column(Integer, primary_key=True)
    name = Column(String)

    simulation = relationship('Simulation', back_populates='measurement', uselist=False)


class Simulation(Base):
    __tablename__ = 'simulation'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    measurement_id = Column(Integer, ForeignKey('measurement.id', onupdate='CASCADE', ondelete='CASCADE'))
    parent_simulation_id = Column(Integer, ForeignKey('simulation.id'), index=True)

    measurement = relationship('Measurement', back_populates='simulation')
    parent_simulation = relationship('Simulation', remote_side=id, backref='child_simulation')

Base.metadata.create_all(engine)

But now I have a strange behaviour using the code. With the first testing code, everything went well:

sess = Session()

measurement = Measurement(name='Measurement_1')
sess.add(measurement)
sess.commit()

simulation1 = Simulation(name='Simulation_1', measurement=measurement, parent_simulation=None)
simulation2 = Simulation(name='Simulation_1.1', measurement=measurement, parent_simulation=simulation1)

sess.add_all((simulation2, simulation1))
sess.commit()

As expected, the output is the following:

 id |      name      | measurement_id | parent_simulation_id
----+----------------+----------------+----------------------
  1 | Simulation_1   |              1 |
  2 | Simulation_1.1 |              1 |                    1

But then, if I change the testing code so the first simulation gets flushed before the second gets initialized...

sess = Session()

measurement = Measurement(name='Measurement_1')
sess.add(measurement)
sess.commit()

simulation1 = Simulation(name='Simulation_1', measurement=measurement, parent_simulation=None)
sess.add_all((simulation1, ))
sess.flush()

simulation2 = Simulation(name='Simulation_1.1', measurement=measurement, parent_simulation=simulation1)
sess.add_all((simulation2, ))
sess.commit()

...the outcome is not as expected anymore:

 id |      name      | measurement_id | parent_simulation_id
----+----------------+----------------+----------------------
  1 | Simulation_1   |                |
  2 | Simulation_1.1 |              1 |                    1

What am I doing wrong? Why is the measurement_id of the first simulation gone once I enter the second one?

I am not sure if I completly understand your data model, but for a Simulation referencing to none or one Measurement, you don't need the

measurement = relationship('Measurement', back_populates='simulation')

in the Simulation class, do you? Try to remove this relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM