JSON को तुरंत चलने लायक SQLAlchemy 2.0 declarative model में बदलता है: Base(DeclarativeBase) class, mapped_column() के साथ Mapped[...] type hints, nullable flags, __tablename__ और Integer primary key।
यह अच्छा शुरुआती बिंदु है जब FastAPI या Flask backend को request JSON, या किसी दूसरे system से download किया data, ऐसी table में store करना हो जिसका अभी कोई model नहीं है।
nullable=True पकड़ा जाए।मॉडल का नाम में class का नाम डालें (default MyModel); __tablename__ उसी नाम का upper snake case रूप है।models.py के रूप में सेव करें। अगर आपके project में पहले से Base है, तो बना हुआ हटाकर अपना import करें, ताकि सभी models एक ही metadata साझा करें।{
"isbn": "978-0-13-468599-1",
"title": "The Pragmatic Programmer",
"pages": 352,
"rating": 4.7,
"available": true,
"published_at": "2019-09-13"
}from datetime import date
from sqlalchemy import Boolean, Date, Float, Integer, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class Book(Base):
__tablename__ = "BOOK"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
isbn: Mapped[str] = mapped_column(String(255), nullable=False)
title: Mapped[str] = mapped_column(String(255), nullable=False)
pages: Mapped[int] = mapped_column(Integer, nullable=False)
rating: Mapped[float] = mapped_column(Float, nullable=False)
available: Mapped[bool] = mapped_column(Boolean, nullable=False)
published_at: Mapped[date] = mapped_column(Date, nullable=False)Hyphen वाला isbn String(255) रहता है, pages Integer बनता है, rating Float, और बिना समय वाली तारीख published_at date hint के साथ Date। हर वैल्यू मौजूद है, इसलिए सभी columns nullable=False हैं।
class Base(DeclarativeBase): pass define करता है और सिर्फ़ वही SQLAlchemy types और datetime नाम import करता है जो सच में इस्तेमाल हुए।Integer/int (बड़ी values के लिए BigInteger), decimals → Float, booleans → Boolean, YYYY-MM-DD → Date/date, date-times → DateTime/datetime, objects और arrays → dict/list के साथ JSON।String(255) होती हैं, या कोई sample वैल्यू 255 कैरेक्टर से लंबी हो तो Text, ताकि table MySQL पर भी बन सके।publishedAt, home-url), तो मूल key column नाम के रूप में दी जाती है: mapped_column("publishedAt", ...)। Python keywords और metadata के अंत में _ लगता है।nullable=True के साथ Mapped[str | None] hint भी होता है।Integer है, जो SQLite पर भी autoincrement होती है; आपके JSON की string id String(255) key बनती है, और बड़ी integer id BigInteger().with_variant(Integer, "sqlite") इस्तेमाल करती है।अगर Pydantic schema के लिए sample request JSON पहले से आपके पास है, तो उसी JSON से SQLAlchemy model बनाएं और तुरंत session.add(Book(**payload)) वाला flow लिखें।
Model Base.metadata पर register होने के बाद alembic revision --autogenerate इस class से create_table migration बनाता है।
str | None hints के लिए Python 3.10+ चाहिए। पुराने versions पर from typing import Optional के साथ Optional[str] लिखें।__tablename__ upper case (BOOK) में है। तब PostgreSQL में raw SQL में इसे quote करना पड़ता है, इसलिए कई projects इसे books में बदल देते हैं।Base की बजाय db.Model से inherit करें।Float binary floating point है; कीमतों के लिए Decimal के साथ Numeric(10, 2) इस्तेमाल करें।id BigInteger की बजाय Integer क्यों इस्तेमाल करता है?SQLite सिर्फ़ ठीक INTEGER PRIMARY KEY के रूप में declare किए column को autoincrement करता है, इसलिए Integer local tests और production का व्यवहार एक जैसा रखता है। सिर्फ़ तब जब आपके data में पहले से 32 bits से बड़ी ids हों, key SQLite variant के साथ BigInteger पर जाती है।
__table_args__) setting है?नहीं। Table connection के default schema में जाती है। किसी दूसरे PostgreSQL schema को target करने के लिए __table_args__ = {"schema": "billing"} खुद जोड़ें।
Column() syntax मिल सकता है?आउटपुट सिर्फ़ 2.0 स्टाइल (Mapped, mapped_column, DeclarativeBase) में है। 1.4 के लिए declarative_base() इस्तेमाल करें और हर line को title = Column(String(255), nullable=False) के रूप में दोबारा लिखें।