2

I have a Django project running on production with PostgreSQL.

I want to spin a separate FastAPI microservice to do a specific task, and I want it to communicate directly with the database I have hooked up with Django.

I do not want to rewrite all the models in FastAPI using pydantic, and at the same time I don't want to make a mistake.

In Django, there is python manage.py inspectdb to automatically generate models using an existing database. Is there an equivalent in FastAPI, SQLAlchemy or Pydantic?

1 Answer 1

5

Have a look at sqlacodegen. It's a tool that reads the structure of an existing database and generates the appropriate SQLAlchemy model code.

It currently offeres a variety of built-in different generators:

  • tables (only generates Table objects, for those who don't want to use the ORM)
  • declarative (the default; generates classes inheriting from declarative_base())
  • dataclasses (generates dataclass-based models; v1.4+ only)
  • sqlmodels (generates model classes for SQLModel)

Declarative is the default, and generates standard SQLAlchemy models which you can use in your FastAPI application. You can also explore the sqlmodels generator as SQLModel is designed to simplify interacting with SQL databases in FastAPI applications (and it was created by the same author as FastAPI).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.