您好,登錄后才能下訂單哦!
Django和Flask都是流行的Python Web框架,它們都提供了ORM(對象關系映射)功能,用于處理數據庫操作。在這兩個框架中,模型繼承是一種常見的做法,用于重用代碼和保持數據庫結構的清晰。下面分別介紹Django和Flask ORM中的模型繼承。
Django支持多種類型的模型繼承,包括單表繼承、多表繼承和代理模型。
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Category(BaseModel):
name = models.CharField(max_length=100)
class Product(BaseModel):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Category(BaseModel):
name = models.CharField(max_length=100)
class Product(BaseModel):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Category(BaseModel):
name = models.CharField(max_length=100)
class Product(BaseModel):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
class ProductProxy(Product):
class Meta:
proxy = True
Flask使用SQLAlchemy作為ORM庫,支持多種類型的繼承,包括單表繼承、多表繼承和混合繼承。
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class BaseModel(db.Model):
__abstract__ = True
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())
class Category(BaseModel):
name = db.Column(db.String(100))
class Product(BaseModel):
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
price = db.Column(db.Float)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class BaseModel(db.Model):
__abstract__ = True
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())
class Category(BaseModel):
name = db.Column(db.String(100))
class Product(BaseModel):
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
price = db.Column(db.Float)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class BaseModel(db.Model):
__abstract__ = True
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())
class Category(BaseModel):
name = db.Column(db.String(100))
class Product(BaseModel):
__table_args__ = (db.ForeignKey('category.id'),)
category_id = db.Column(db.Integer)
price = db.Column(db.Float)
總結:Django和Flask都支持多種類型的模型繼承,具體實現方式略有不同。在實際項目中,可以根據需求和場景選擇合適的繼承方式。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。