1

I am trying too update the JSON datatype column of postgresql table using Sqlalchemy binaryexpression in python.

Example

unit_price = 10.10
final_data = {
    "price_details": {
        "unit_price":unit_price,
        "total_amt":testmodel.qty * unit_price
    }
}

test_db = session.query(testmodel).filter(testmodel.id >= 10)
test_db.update(final_data,synchronize_session=False)

In above example i am trying to calculate total_amt using binaryexpression. But I am getting error.

StatementError: (exceptions.TypeError) <sqlalchemy.sql.elements.BinaryExpression object at 0x6024810> is not JSON serializable  

1 Answer 1

1

In order to use DB values in your update, you have to use the DB JSON features instead of passing serialized JSON from Python – not to mention that the Python JSON encoder has no idea what to do with an SQL expression. Consulting the Postgresql JSON functions and operators it seems that json_build_object() or its JSONB variant are what you're looking for:

unit_price = 10.10
final_data = {
    "price_details": func.json_build_object(
        "unit_price", unit_price,
        "total_amt", testmodel.qty * unit_price
    )
}

test_db = session.query(testmodel).filter(testmodel.id >= 10)
test_db.update(final_data, synchronize_session=False)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.