SoFunction
Updated on 2024-11-14

python automatically generate model file process details

Generation method

If you want to automatically generate a model file in Python, you can use the command sqlacodegen to generate the corresponding model file.

sqlacodegen You can install it by piping to.

pip install sqlacodegen

Format:

sqlacodegen mysql+pymysql://username:password@host/database_name > 

Description:

  • mysql+pymysql : Indicates the connection to the database.
  • username : the username to connect to the MySQL database
  • password : The password of the user who connects to the MySQL database.
  • host : the host address of the database
  • database_name : the name of the database for which the model needs to be generated [must be the database name].

Question: What if I only want to generate a model file for a specific table in the database?

The answer is:

Just add a --table argument to sqlacodegen

Case in point.

👉⚡️sqlacodegen --tables products mysql+pymysql://root:[email protected]/shopify > 
👉⚡️ls

Results:

👉⚡️cat  
# coding: utf-8
from sqlalchemy import CHAR, Column, String, Text, text
from  import INTEGER
from  import declarative_base

Base = declarative_base()
metadata = 


class Product(Base):
  __tablename__ = 'products'

  id = Column(INTEGER(16), primary_key=True)
  title = Column(String(256), nullable=False, server_default=text("''"))
  product_id = Column(INTEGER(16))
  shop_url = Column(String(120))
  body_html = Column(Text)
  vendor = Column(String(64))
  product_type = Column(String(64))
  created_at = Column(CHAR(30))
  updated_at = Column(CHAR(30))
  handle = Column(String(256))
  published_at = Column(CHAR(30))
  template_suffix = Column(String(256))
  tags = Column(String(256))
  published_scope = Column(CHAR(10), nullable=False, server_default=text("'web'"))
👉⚡️

This is the whole content of this article.