我使用的是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?
这个答案纯粹是我个人的看法。可能还有一个我不知道的更好的技术原因。
两者都怎么样?伟大的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
中,主要是因为函数的措辞更自然,这通常意味着更适合;-)