I have a table of 'Clients' where a client can be a child of another client.
Here's the table definition.
[ClientID] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[VPFSID] [varchar](50) NOT NULL,
[Type] [varchar](25) NULL,
[ROHostID] [varchar](60) NOT NULL,
[RWHostID] [varchar](60) NOT NULL,
[ParentClientID] [int] NULL
In SQLAlchemy, how do I create the relationship between the ParentClientID and ClientID. I put together this class using declarative but I'm not sure if it's valid or not. A Client can have many children, but can only have a single parent, so it's a Many-to-1 relationship
class Client(Base):
""" Client Filesystems """
__tablename__ = 'Client'
client_id = Column('ClientID', int, primary_key=True, nullable=Flase)
name = Column('name', String(50), nullable=False)
vpfs_id = Column('VPFSID', String(50), nullable=False)
type = Column('Type',String(25))
ro_host_id = Column('ROHostID', String(60), ForeignKey('DataMover.HostID'), nullable=False)
rw_host_id = Column('RWHostID', String(60), ForeignKey('DataMover.HostID'), nullable=False)
rw_host = relation('Datamover',backref="rw_clients")
ro_host = relation('Datamover',backref="ro_clients")
parent_client_id = Column('ParentClientID',int,ForeignKey('Client.ClientID'))
parent = relation('Client',ForeignKey('Client.ClientID'))
Any suggestions on accomplishing this?
Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.
The comments class attribute defines a One-to-Many relationship between the Post model and the Comment model. You use the db. relationship() method, passing it the name of the comments model ( Comment in this case). You use the backref parameter to add a back reference that behaves like a column to the Comment model.
If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.
class Client(Base):
...<snip>...
parent = relation('Client', remote_side=[client_id])
Docs here: orm/self_referential.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With