'SQLAlchemy Joined Table Inheritance: Problem adding objects

I'm having problems trying to add inherited objects with SQLAlchemy following the instructions in https://docs.sqlalchemy.org/en/14/orm/inheritance.html to implement Joined Table Inheritance.

I'm using a PostgreSQL version 14 as a database engine.

Here is my Base configuration:

import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.automap import automap_base

db_string = os.environ['DB_STRING']

engine = create_engine(db_string)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = automap_base()
Base.query = db_session.query_property()
Base.prepare(engine, reflect=True)

Here is Instrument (parent class) definition:

from sqlalchemy import Column,  String
from context_model.database import Base


class Instrument(Base):
    __tablename__ = "instrument"

    _id = Column(String, primary_key=True)
    discriminator = Column(String)

    __mapper_args__ = {
        'polymorphic_identity': 'instrument',
        'polymorphic_on': discriminator

Here is Bond (child class) definition:

import datetime as dt

from sqlalchemy import Column, Integer, Float, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from context_model.instrument.instrument import Instrument


class Bond(Instrument):
    __tablename__ = "bond"

    _id = Column(String, ForeignKey("instrument._id"), primary_key=True)
    _provider_bbg_id = Column(String)

    __mapper_args__ = {
        'polymorphic_identity': 'bond'
    }

When I try to add a Bond instance and persist it to the database:

Bond = Base.classes.bond
bond = Bond()
bond._id = "0"
bond._provider_bbg_id = "XXX"
db_session.add(bond)
db_session.commit()

appears the following error message:

sqlalchemy.exc.IntegrityError: (psycopg2.errors.ForeignKeyViolation) insert or update on table "bond" violates foreign key constraint "bond__id_fkey"
DETAIL:  Key (_id)=(0) is not present in table "instrument"."

It seems to me that the inheritance is not working for some reason, did I define well the Instrument (parent) and Bond (child) classes ?, maybe do I need to use another type of Base ? (I'm using automap_base )

Thanks in advance for your help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source