Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to One relationship with SQLAlchemy in the same table

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?

like image 736
Kurt Telep Avatar asked Apr 13 '11 12:04

Kurt Telep


People also ask

How will you implement many to many relationship in SQLAlchemy?

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.

How do you create a one to many relationship in flask SQLAlchemy?

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.

Should I use SQLAlchemy core or ORM?

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.


1 Answers

class Client(Base):
    ...<snip>...
    parent = relation('Client', remote_side=[client_id])

Docs here: orm/self_referential.html

like image 166
Gary van der Merwe Avatar answered Sep 30 '22 20:09

Gary van der Merwe