I'm looking for a way to create hierarchy in form of child parent relationship between two or more instances of same class.
How would one go about creating such objects from nested dictionary like in example ? Is this even possible ? Is there some other way which would be recommended to do such task?
# -*- coding: utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, exists
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, String
Base = declarative_base()
class Person(Base):
__tablename__ = 'person';
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
parent_id = Column(Integer, ForeignKey('person.id'))
def __init__(self, **kwargs):
self.parent_id = kwargs.get('parent_id', None)
self.name = kwargs.get('name')
self.team = kwargs.get('team', [])
# Is it possible to create more object of this type
# and establish that their parent_id is ID of this object?
def __repr__(self):
return """
ID: {}
Name: {}
ParentID: {}
""".format(self.id, self.name, self.parent_id)
engine = create_engine('sqlite:///db.sqlite3')
Base.metadata.create_all(engine)
connection = engine.connect()
Session = sessionmaker(bind=engine)
session = Session()
alice = {'name' : 'Alice'}
bob = {'name' : 'Bob', 'team' : [alice, ]}
p1 = Person(bob)
session.add(p1)
session.commit()
I understand the iterative approach where I would first create parent object, then iterate over possible children and create them. I'm curious if there is a way to do this inside constructor rather than from 'outside' with loops.