python - sqlalchemy 模型的数据和逻辑分离

标签 python python-3.x sqlalchemy data-access-layer business-logic-layer

在下面的示例中,我应该将 get_friend 方法保留在类中,还是应该将其移到类之外,因为我想将数据结构与业务逻辑分开? 最佳做法是什么? 不要因为类(class)太小而产生偏见,这只是一个例子,但类(class)可以更大。

from sqlalchemy import Column, Integer, String, Float, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class User(Base):
    id = Column("id", Integer, primary_key=True)
    friends = relationship("Friends")

    def get_friend(self, friend_name):
        for friend in self.friends:
            if friend.name == friend_name:
                return friend
        return None

最佳答案

我从未使用过 python,仅根据 DAL 和 BLL 来回答这个问题。

如果我没记错的话,User 就是你的持久模型。理想情况下,它应该只处理持久性问题。它不应该处理域逻辑;该部分应移至业务逻辑层或您的服务类。

嗯,没有任何地方为此制定任何硬性规则;但有“良好实践”/“建议”/“范式”/“模式”。这些是根据大型社区的更广泛经验定义的。

因此,您最好考虑将该方法移至 BLL。

关于python - sqlalchemy 模型的数据和逻辑分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48516893/

相关文章:

python - 将子列表作为对象而不是列表复制到主列表中

python - pydantic.error_wrappers.ValidationError : 11 validation errors for For Trip type=value_error. 缺失

python - plotly.figure_factory.create_scatterplot 停止工作?

python - 避免在 Sphinx 文档中扩展 sys.argv 关键字参数

python - 将整数添加到排序列表 - 递归

python - Pywinauto app = Application.start() 不起作用并给出错误

python - SQLAlchemy 从两个具有空 LEFT JOIN 的表中选择返回空结果

python - sqlalchemy在一对多关系中添加 child

Python:引发 argparse.ArgumentError 后,argparse 引发一般错误

python - 如何跨多个文本文件查找字典中键的频率?