生成方式
Python中想要自動生成 model文件可以通過 sqlacodegen這個命令來生成對應(yīng)的model文件
sqlacodegen 你可以通過pip去安裝:
pip install sqlacodegen
格式:
sqlacodegen mysql+pymysql://username:password@host/database_name > model.py
說明:
mysql+pymysql : 表示連接數(shù)據(jù)庫的連接方式 username : 連接MySQL數(shù)據(jù)庫的用戶名 password : 連接MySQL數(shù)據(jù)庫用戶對應(yīng)的密碼 host : 數(shù)據(jù)庫的主機(jī)地址 database_name : 需要生成model的數(shù)據(jù)庫名【一定是數(shù)據(jù)庫名】問題: 如果只想生成數(shù)據(jù)庫中指定表的model文件怎么辦?
答案就是:
給 sqlacodegen 加一個 --table 的參數(shù)即可
案例:
👉⚡️sqlacodegen --tables products mysql+pymysql://root:[email protected]/shopify > products.py👉⚡️lsproducts.py
結(jié)果:
👉⚡️cat products.py # coding: utf-8from sqlalchemy import CHAR, Column, String, Text, textfrom sqlalchemy.dialects.mysql import INTEGERfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()metadata = Base.metadataclass 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'"))👉⚡️
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)之家。
新聞熱點
疑難解答
圖片精選