0

I am trying to insert a json file into postgress db using flask/sqlalchemy however I'm running into

TypeError: 'farmers' is an invalid keyword argument for Farmer

This is my upload script:

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):
    Farmers = db.Column(db.Integer, primary_key=True)
    W = db.Column(db.Integer)
    Z = db.Column(db.Integer)
    J1_I = db.Column(db.Integer)
        
def insert_data():
 
    f1 = Farmers(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()

This is the json file in question, however i dont think this is an issue as i'm able to read it in cmd:

{
    "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 why i'm not able to upload the data?

1 Answer 1

1

The model constructor won't accept a list, you need to pass each dictionary individually:

farmer_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}]}
farmers = [Farmer(**data) for data in farmer_data["farmers"]]
db.session.add_all(farmers)
db.session.commit()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.