python - Django 模型中的紧耦合

标签 python django django-models single-responsibility-principle

我的 Django 模型包含 incident_typeclosed 字段。基于这个字段,我想返回呈现一些文本的函数。

在模型中使用这样的 get_renderer 方法是否可以,或者我应该将此逻辑移至其他地方?在我看来,这种方法违反了单一职责原则。

class Incident(models.Model):
    BAD_RESPONSE = 'bad_response'
    SLOW_RESPONSE = 'slow_response'
    INCIDENT_TYPE_CHOICES = (
        (BAD_RESPONSE, 'Webpage is not available'),
        (SLOW_RESPONSE, 'Webpage is slow'),
    )

    incident_type = models.CharField(max_length=50, choices=INCIDENT_TYPE_CHOICES)
    closed = models.BooleanField()

    def get_renderer(self):
        if self.incident_type == self.BAD_RESPONSE:
            if self.closed:
                return render_page_up_screen
            else:
                return render_page_down_screen

最佳答案

我认为将此方法定位在您的 View 层中的某处会更合适。使您的模型与网络和渲染相关概念保持松散耦合通常是一种很好的做法。它使模型保持灵 active ,更能适应变化。

get_renderer() 移动到您的 View 中应该很简单?它仍然可以通过 Indcident 实例访问 indicdent_typeclosed 字段以做出其呈现决定。

关于python - Django 模型中的紧耦合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302478/

相关文章:

Django 计算具有重复值的行

Python:通过搜索 XML 树将值附加到现有字典条目

python - 基于 Django 文件的 session - 文件名太长

python - Gitlab CI/CD 部署 Django Docker 容器

sql - Django 中 GROUP BY 注释的聚合

python - "Matching"/Django中跨数据库的关系数据

Python - 如何从字符串中删除隐藏的符号?

python - 为什么我的 Django View 装饰器没有收到传递给它的请求?

python - Django 1.5.4 无法在开发服务器上提供 css

python - 更新 django 模型中的对象