Python 服务层
我正在使用 Python 2.7.2 和 SQLAlchemy 0.9.3。一个部门可以有很多小组。
class Department(Base):
id = Column(Integer, primary_key=True)
groups = relationship("Group", backref="department")
...
class Group(Base):
id = Column(Integer, primary_key=True)
department_id = Column(Integer, ForeignKey('departments.id'))
...
那么get_groups和add_group这两个方法应该放在哪儿呢?是在 DepartmentService 里,还是在 GroupService 里?
class DepartmentService(object):
def get_groups(self, dept_id):
...
def add_group(self, dept_id, group):
...
class GroupService(object):
def get_groups(self, dept_id):
...
def add_group(self, dept_id, group):
...
或者我应该在 DepartmentService 里调用 GroupService 呢?
1 个回答
1
这只是我个人的看法,可能还有我不知道的更好的技术理由。
那两者都可以吗?这个很棒的 backref 功能会帮你保持数据库的同步:
class DepartmentService(object):
def get_groups_by_department(self, dept_id):
...
def add_group_to_department(self, dept_id, group):
...
class GroupService(object):
def get_department(self, dept_id):
...
def add_to_department(self, dept_id, group):
...
如果让我选择一个,我会把它放在 GroupService
里,主要是因为这些函数的表述更自然,这通常意味着更合适 ;-)