My first try with an ORM, trying to understand how it works, but having a bit of a challenge:
What I'm trying to do is, fit a JSON from an API into a SQLAlchemy model, and then bulk insert all entries into my database. But for some reason I'm getting an error in SQLAlchemy.
From what I understand of the error, at some point in time, when assigning the data to my model, it's being converted into a dict, when I thought it should be a list of class objects.
My expected result is a successful insert of all the entries. Can anybody help figuring what I might be doing wrong?
Appreciate.*
The error
sqlalchemy.exc.ProgrammingError:
(mysql.connector.errors.ProgrammingError)
Failed processing pyformat-parameters;
Python 'dict' cannot be converted to a MySQL type
The JSON:
{
"all_orders": [
{
"id": 456215587,
"created_at": "2018-11-04T23:18:18-02:00",
"order_number": null,
},
{
"id": null,
"created_at": "2018-11-04T23:18:18-02:00",
"order_number": 1982,
}]
}
The Function
def update_orders(all_orders):
cursor = db_cursor()
session = db_session()
orders_entries = []
for orders in all_orders:
order_id = orders.get("id", {})
order_number = orders.get("order_number", {})
created_at = orders.get("created_at", {})
new_entry = SalesOrders(order_id=order_id,
order_number=order_number,
created_at=created_at)
orders_entries.append(new_entry)
session.add_all(orders_entries)
session.commit()
The Model
class SalesOrders(db.Model):
__tablename__ = 'sales_orders'
id = Column(Integer, nullable=False, index=True)
order_id = Column(String(50), primary_key=True, server_default=text("''"))
order_number = Column(String(50))
created_at = Column(String(100))
EDIT to make it verifiable.
The function .get() is was creating a dictionary, instead of a None object, and SQLAlchemy wasn't able to insert a Python Dictionary.