SQLAlchemy:检查RelationshipProperty是否为标量
我想通过编程的方式构建一个查询,在这个查询中,我需要对一个关系应用过滤器,使用的是 any()
或 has()
。我的代码并不知道这个关系是一对一还是一对多,所以为了避免出现错误:
InvalidRequestError: 'any()' not implemented for scalar attributes. Use has().
.. 我现在必须写一个这样的测试:
try:
new_filter = relationship.any(filter)
except InvalidRequestError:
new_filter = relationship.has(filter)
我更希望能用一个 if 语句。请问 RelationshipProperty 有没有什么属性可以告诉我它是否是标量(即单一值)?
在 RelationshipProperty 的文档中没有提到类似 is_scalar
或者获取 uselist
的方法,我在这里也找不到这样的属性:
>>> dir(relationship)
['__add__', '__and__', '__class__', '__clause_element__', '__delattr__', '__delete__', '__dict__', '__div__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__rshift__', '__rsub__', '__rtruediv__', '__selectable__', '__set__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', '_of_type', '_parententity', '_query_clause_element', '_supports_population', 'adapt_to_entity', 'adapter', 'any', 'any_op', 'asc', 'between', 'class_', 'collate', 'comparator', 'concat', 'contains', 'desc', 'dispatch', 'distinct', 'endswith', 'expression', 'extension_type', 'get_history', 'has', 'has_op', 'hasparent', 'ilike', 'impl', 'in_', 'info', 'is_', 'is_aliased_class', 'is_attribute', 'is_clause_element', 'is_instance', 'is_mapper', 'is_property', 'is_selectable', 'isnot', 'key', 'label', 'like', 'match', 'notilike', 'notin_', 'notlike', 'nullsfirst', 'nullslast', 'of_type', 'of_type_op', 'op', 'operate', 'parent', 'property', 'reverse_operate', 'startswith', 'timetuple']
这个问题是关于 SQLAlchemy 0.9 的。
1 个回答
5
在查看关系属性的值时,有一个属性叫做 impl
,如果这个关系是单一的(也就是只关联一个对象),那么它的类型就是 sqlalchemy.orm.attributes.ScalarObjectAttributeImpl
。所以我现在采用了以下的测试方法:
is_scalar = isinstance(relationship.impl, ScalarObjectAttributeImpl)