SQLAlchemy - 关联表与主连接中的日期问题
我正在用SQLAlchemy定义我的映射,基本上快完成了,只剩下一件事。我有一个“资源”对象和一个叫“关系”的关联表,里面有几个属性,并且有两个资源之间的关系。我一直在尝试做的事情几乎成功了,就是在资源对象上提供两个属性:父级和子级,以便能够遍历由关联表存储的树形结构。两个属性之间的关系只持续一段时间,所以有开始和结束日期。一次只能有一个资源作为另一个资源的父级。
我的问题是,如果我结束一个关系并创建一个新的,父级属性却没有更新。我在想,可能是资源的父级属性的primaryjoin有问题。
这里有一些代码:
resource_table = model.tables['resource']
relation_table = model.tables['resource_relation']
mapper(Resource, resource_table,
properties = {
'type' : relation(ResourceType,lazy = False),
'groups' : relation(Group,
secondary = model.tables['resource_group'],
backref = 'resources'),
'parent' : relation(Relation, uselist=False,
primaryjoin = and_(
relation_table.c.res_id == resource_table.c.res_id,
relation_table.c.end_date > func.now())),
'children' : relation(Relation,
primaryjoin = and_(
relation_table.c.parent_id == resource_table.c.res_id,
relation_table.c.end_date > func.now()))
}
)
mapper(Relation, relation_table,
properties = {
'resource' : relation(Resource,
primaryjoin = (relation_table.c.res_id == resource_table.c.res_id)),
'parent' : relation(Resource,
primaryjoin = (relation_table.c.parent_id == resource_table.c.res_id))
}
)
oldrelation = resource.parent
oldrelation.end_date = datetime.today()
relation = self.createRelation(parent, resource)
# Here the relation object has not replaced oldrelation in the resource object
有什么想法吗?
谢谢,
理查德·洛佩斯
1 个回答
0
在比较日期的时候,可以考虑用 >=
代替 >
。