Reputation: 4080
In my db I have one to many model (parent vs many children). Content of files :
class Parent(Base):
__tablename__ = 'parent'
id = Column('id', bigint, primary_key=True)
name = Column('name', TEXT, nullable=False)
lname = Column('lname', TEXT, nullable=False)
register_date = Column('register_date',DateTime(timezone=True), default=datetime.datetime.utcnow)
children = relationship('Child')
def __init__(self, id, name,lname,register_date):
self.id=id
self.name=name
self.lname=lname
class Child(Base):
__tablename__ = 'children'
id = Column('id', bigint, primary_key=True)
parent_id = Column('parents', ForeignKey('parents.id'), nullable=False)
name = Column('name', TEXT, nullable=False)
lname = Column('lname', TEXT, nullable=False)
register_date = Column('register_date',DateTime(timezone=True),
parent = relationship('Parent', back_populates="children")
def __init__(self, id, name, lname, parent):
self.id=id
self.name=name
self.lname=lname
self.parent=parent
My input of the program is an XML file in the following format :
<Parent>
<name> fname_example </name>
<lname> lname_example </lname>
<id> id_example </id>
<Children>
<Child>
<name> fname_example </name>
<lname> lname_example </lname>
<id> id_example </id>
</Child>
<Child>
<name> fname_example </name>
<lname> lname_example </lname>
<id> id_example </id>
</Child>
</Children>
</Parent>
<Parent>
....
</Parent>
After parsing this XML file I have a list of parents and of children. At first, I'm saving the parents :
session.add_all(parents)
And after a few checks I'm also saving the children :
session.bulk_save_objects(children)
My issue is that in this way the mapper doesn't map the parent to the children and in the insert query I see that null is mapped as the parent :
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush.
To begin a new transaction with this Session, first issue Session.rollback().
Original exception was: (psycopg2.errors.NotNullViolation) null value in column "parent" violates not-null constraint
DETAIL: Failing row contains (1, null, 'Roger', 'Prince','01-10-2019')
Upvotes: 0
Views: 144
Reputation: 4080
The solution in my case : I added the next row to the init method of the child ; self.parent_id=parent.id
Upvotes: 1