Python Automatically Generates ORM Entity Class Samples Using sqlacodegen
- 2021-06-28 09:23:09
- OfStack
This article provides an example of how Python automatically generates ORM entity classes using sqlacodegen.Share it for your reference, as follows:
In the previous article, Python Popular ORM Framework sqlalchemy Installation and Use, we manually created a file named Infos.py and then defined a
News
Class, treat this class as with us
news
Mapping of data tables.
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String
class News(Base):
# Table Name
__tablename__ = 'news'
# news Exterior id field
id = Column(Integer, primary_key=True, autoincrement=True)
# news Exterior title field
title = Column(String(length=255), nullable=False)
Now let's take a look
sqlacodegen
This tool automatically generates files like those above.
1. Install sqlacodegen
#cd Project Virtual Environment
# implement
./python3 -m pip install sqlacodegen
2. Use sqlacodegen to generate columns
# Note or execute in the virtual environment directory
./sqlacodegen --tables fund --outfile ../../mappers/Found.py mysql+pymysql://root:root@localhost/test?charset=utf8
--tables
Specify the name of the data table and we will generate the fund Fund data table.
--outfile
Specify the output file name.
3. The generated Fund.py file code is as follows:
# coding: utf-8
from sqlalchemy import Column, DateTime, Numeric, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = 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 by hand.
More readers interested in Python-related content can view this site's topics: Summary of Python's Common Database Operating Skills, Summary of Python Mathematical Operating Skills, Python Data Structure and Algorithms Tutorial, Summary of Python Function Usage Skills, Summary of Python String Operating Skills, andIntroduction to Python and Advanced Classic Tutorials and Summary of Python File and Directory Operating Skills
I hope that the description in this paper will be helpful to everyone's Python program design.