Skip to main content
 首页 » 编程设计

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

2024年09月07日16三少

在下面的示例中,我应该将 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。