SQLALCHEMY How to define relationship

Viewed 22

I have the following ER Diagram and I need to define the relationship using SQLALCHEMY.

enter image description here

I defined all the tables, type of data, fields and Primary_Key and ForeignKey. I just need to make the relationship. This is an actual Diagram.

ERD

The code is the following(And it runs well, just need to add the relationship)

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date, Float, ForeignKey

Base = declarative_base()

class BALANCE(Base): # clases las llamare en mayuscula
    __tablename__='balance'
    balanceID= Column(Integer, autoincrement=True,primary_key=True) 
    version=Column(String)
    date = Column(String)

    def __repr__(self): # date va sin comillas 
        return "<BALANCE(balanceID='{}', version='{}', date='{}')>".format(self.balanceID, self.version, self.date)
    

class CMG_BALANCE(Base):
    __tablename__='CMg_balance'
    balanceID= Column(Integer, autoincrement=True,primary_key=True) 
    barraID=Column(String, ForeignKey('barra.barraID'))
    date = Column(String)
    CMg_USD_MWh=Column(Float)
    CMg_CLP_KWh=Column(Float)

    def __repr__(self):
        return "<CMG_BALANCE(balanceID='{}', barraID='{}',date='{}',CMg_USD_MWh='{}',CMg_CLP_KWh='{}')>".format(self.balanceID,self.date,self.CMg_USD_MWh,self.CMg_CLP_KWh)

class BARRA(Base):
    __tablename__='barra'
    barraID=Column(String, primary_key=True )
    comentarios=Column(String)

    def __repr__(self):
        return "<BARRA(barraID='{}',comentarios='{}')>".format(self.barraID, self.comentarios)

I still have to define the relationship to finish the design of the DB. Could you help me how??

Appreciate your help, have a nice daay !!

1 Answers

You can import relationship from sqlalchemy.orm and define a relationship like that:

from sqlalchemy import Column, ForeignKey, Integer, Table
from sqlalchemy.orm import declarative_base, relationship

Base = declarative_base()

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    children = relationship("Child", back_populates="parent")


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent.id"))
    parent = relationship("Parent", back_populates="children")
Related