Django的设计鼓励松耦合以及对应用程序中不同部分的严格分割,把数据存取逻辑、业务逻辑和表现逻辑组合在一起的概念被称为Model-View-Controller模式,在Django中M、V和C各自的含义

框架层

描述

M

数据存取部分,由Django数据层处理

V

选择显示哪些数据以及怎样显示的部分,由视图和模板处理

C

根据用户输入委派视图的部分,由Django框架根据URLconf设置,对给定URL调用适当的Python函数

由于C由框架自行处理,而Django里更关注模型Model、模板Template和视图Views,因此被称为MTV框架,在MTV开发模式中:

框架层

描述

Model

数据存取层,处理与数据相关的所有事务,即如何存取如何验证有效

Template

表现层,处理与表现相关的决定,即如何在页面或者其他类型的文档中进行显示

View

业务逻辑层,包含存取模型及调取恰当模板的相关逻辑,可以看作是模型和模板之间的桥梁

与大多数MVC框架稍微有些不同,在Django对MVC的诠释中,视图用来描述要展现给用户的数据,而不是数据如何展现以及展现哪些数据,同类框架中提倡控制器负责决定向用户展现那些数据,而视图仅决定如何展现数据,而不是展现哪些数据

以往的开发模式

class ProductInfo:
def __init__(self):
self.product_name = None
self.id = None
self.price = None
self.manufacturer = None
from MTV.module_product import ProductInfo

class ProductView:
def print_product(self):

product = ProductInfo() # 实例化类,但也产生了耦合点
print(f"Name: {product.product_name}")
print(f"Price: {product.price}")
print(f"Manufacturer: {product.manufacturer}")


if __name__ == '__main__':
show_product = ProductView()
show_product.print_product()

将这个例子改为MVC模式

class ProductInfo:
"""
model
"""
def __init__(self):
self.product_name = None
self.id = None
self.price = None
self.manufacturer = None
class ProductView:
"""
view
"""
def print_product(self, product):
print(f"Name: {product.product_name}")
print(f"Price: {product.price}")
print(f"Manufacturer: {product.manufacturer}")
from MTV.view_product import ProductView
from MTV.model_product import ProductInfo


class ProductController:
"""
控制器
"""

def __init__(self, product, view):
self.product = product
self.product_view = view

def refresh_view(self):
"""

:return:
"""
self.product_view.print_product(self.product)

def update_model(self, product_name, price, manufacturer):
"""
更新对象属性
:param product_name:
:param price:
:param manufacturer:
:return:
"""

self.product.product_name = product_name
self.product.price = price
self.product.manufacturer = manufacturer


if __name__ == '__main__':
controller = ProductController(ProductInfo(), ProductView())
controller.refresh_view()
controller.update_model("newname", 15, "davieyang")
controller.refresh_view()