SoFunction
Updated on 2024-12-10

Python using sqlacodegen automatically generate ORM entity class example

This article example describes Python automatically generate ORM entity classes using sqlacodegen. Shared for your reference, as follows:

In a previous post, thePython popular ORM framework sqlalchemy installation and useWe have manually created a file calledfile, and then defines aNewsclass, treating this class as the same as ournewsMapping of data tables.

from  import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String
class News(Base):
  # Table name
  __tablename__ = 'news'
  # id field in the news table
  id = Column(Integer, primary_key=True, autoincrement=True)
  # title field in the news table
  title = Column(String(length=255), nullable=False)

Now let's see.sqlacodegenThis tool, automatically generates class files like the one above.

1. Installation of sqlacodegen

#cd project virtual environment
#Execute
./python3 -m pip install sqlacodegen

2. Use sqlacodegen to generate case histories

# Note that it is still executed in the virtual environment directory
./sqlacodegen --tables fund --outfile ../../mappers/ mysql+pymysql://root:root@localhost/test?charset=utf8

--tablesSpecify the datasheet name we give to the FUND fund datasheet to generate.
--outfileSpecifies the name of the output file.

3. GeneratedThe file code is as follows:

# coding: utf-8
from sqlalchemy import Column, DateTime, Numeric, String
from  import declarative_base
Base = declarative_base()
metadata = 
class Fund(Base):
  __tablename__ = 'fund'
  code = Column(String(50), primary_key=True)
  name = Column(String(255))
  NAV = Column(Numeric(5, 4))
  ACCNAV = Column(Numeric(5, 4))
  updated_at = Column(DateTime)

That way you don't have to write it manually.

Readers interested in more Python related content can check out this site's topic: theSummary of common database manipulation techniques in Python》、《Summary of Python Math Operations Tips》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope the description of this article will help you in Python programming.