[Python] Many to One relationship with SQLAlchemy in the same table

Discussão em 'Python' iniciado por Stack, Março 12, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página