Goal: Object has two attributes: First attribute points to a Python list backed by a JSON array. Second attribute points to a specific index in that first attribute's list.
Problem: Second attribute listed above currently doesn't work.
Background: SQLAlchemy attribute with a TypeDecorator derived from JSONB works as expected. When trying to index the attribute (extract the second value in the array, for instance), I get a JSONElement (derived from BinaryExpression) instead of an actual result.
Attributes in my class are defined as follows:
class MyClass...
values_to_hold = Column(MyArr)
MyClass.second_val_in_arr = MyClass.values_to_hold[1]
second_val_in_arr returns a JSONElement instead of the result as expected. Explicitly adding astext (MyClass.values_to_hold[1].astext) does not help either.
If I set:
MyClass.second_val_in_arr = MyClass.values_to_hold
then second_val_in_arr returns the actual array as expected. But if I try to perform an index operation on the array (as above), then it suddenly returns a JSONElement.
Additional info:
MyArr is a TypeDecorator as below:
class MyArr(TypeDecorator):
impl = JSONB
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
def process_result_value(self, value, dialect):
if value:
return list(value)
else:
return list()
(Note that coerce_compared_value is explicitly overridden because of the special logic required for JSON as per the docs).