any()我想以编程方式构建一个查询,在其中使用or将过滤器应用于关系has()。我的代码不知道关系是一对一还是一对多,因此要避免此错误:
InvalidRequestError: 'any()' not implemented for scalar attributes. Use has().
Run Code Online (Sandbox Code Playgroud)
..我目前必须编写这样的测试:
try:
new_filter = relationship.any(filter)
except InvalidRequestError:
new_filter = relationship.has(filter)
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用 if 语句。RelationshipProperty 是否有一个属性来指示它是否是标量?
RelationshipProperty的文档没有提到任何类似is_scalar或任何 getter 的东西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']
Run Code Online (Sandbox Code Playgroud)
该问题涉及 SQLAlchemy 0.9。
查看关系属性的值,如果关系是标量,则有一个属性impl属于标量类型。sqlalchemy.orm.attributes.ScalarObjectAttributeImpl所以我现在进行了以下测试:
is_scalar = isinstance(relationship.impl, ScalarObjectAttributeImpl)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
799 次 |
| 最近记录: |