I am trying to add a json file into my Postgres database using sqlalchemy and flask however i'm getting the error. I've created the table Farmers in my pgadmin however now im trying to add the json data in f1.
Error:
line 20, in insert_data
f1 = Farmers(farmers={{"W":1000000,"Z":22758,"J1_I":0.66},{"W":3500000,"Z":21374,"J1_I":2.69},{"W":2500000,"Z":14321,"J1_I":0.76},{"W":2500000,"Z":14321,"J1_I":0.76}})
TypeError: unhashable type: 'dict'
The upload.py file is:
import os
import flask
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, send_from_directory
from sqlalchemy.dialects.postgresql import JSON
APP = Flask(__name__)
APP.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:admin@localhost:5432/flaskwebapp'
db = SQLAlchemy(APP)
class Farmers(db.Model):
id = db.Column(db.Integer, primary_key=True, index=True)
W = db.Column(db.Integer)
Z = db.Column(db.Integer)
J1_I = db.Column(db.Float)
#db.create_all()
def insert_data():
f1 = Farmers(farmers={{"W":1000000,"Z":22758,"J1_I":0.66},{"W":3500000,"Z":21374,"J1_I":2.69},{"W":2500000,"Z":14321,"J1_I":0.76},{"W":2500000,"Z":14321,"J1_I":0.76}})
db.session.add(f1)
db.session.commit()
print('Data inserted to DB!')
insert_data()
Json array object file:
{
"farmers":[ {
"W":1000000,
"Z":22758,
"J1_I":0.66
},
{
"W":3500000,
"Z":21374,
"J1_I":2.69
},
{
"W":2500000,
"Z":14321,
"J1_I":0.76
},
{
"W":2500000,
"Z":14321,
"J1_I":0.76
}]}
Any ideas on how to fix this?
CodePudding user response:
You are trying to store multiple objects in your database at once. For this you have to create an object of type Farmers
for each element of the list. You can then store these created objects in the database.
def insert_data():
# The list of objects with their associated data.
farmers = [
{"W":1000000,"Z":22758,"J1_I":0.66},
{"W":3500000,"Z":21374,"J1_I":2.69},
{"W":2500000,"Z":14321,"J1_I":0.76},
{"W":2500000,"Z":14321,"J1_I":0.76}
]
# An object is created for each record and added to a list.
farmer_objects = [Farmers(**data) for data in farmers]
# The objects created are added to the session.
db.session.add_all(farmer_objects)
# The session is closed and the objects it contains are saved.
db.session.commit()
By the way, the JSON file contains an object with a list of objects that contain the data. The list is accessible under the key "farmers". So you have to extract the list from the loaded file first.
For some reason you are trying to pass a dict.