Search code examples
sqlalchemyvisualizationentity-relationship

How can I automatically generate an ER diagram to visualize table relationships of an ORM in SQLAlchemy?


I am trying to find a way to generate an entity relationship diagram based on an ORM which has been created using SQLAlchemy. The ORM might look like this and contain multiple tables, that are related via Primary and Foreign Keys:

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base

# declarative base class
Base = declarative_base()

# an example mapping using the base
class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    nickname = Column(String)

I already found https://pypi.org/project/ERAlchemy/ but it doesn't help since it is only displaying general relations between tables. I would like to see exactly which columns are related to each other via primary key and foreign keys though, so the arrows should be displayed exactly between the related columns.

Anyone knows of a good alternative here?


Solution

  • I found my own solution in the meantime. It is adding a little bit more complexity, but delivers a great output. Just sharing here as well in case s.o. else has a similar use case:

    1. I locally setup a mysql database (using the mysql docker image)
    2. Used Base.metadata.create_all(engine) to actually generate the (empty) tables in the local database
    3. Used mysql workbench's database reverse engineering feature, which automatically generates an interactive ER diagram