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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。