使用 SQLAlchemy 烧瓶将 json 文件插入 postgres

Inserting json file into postgres with SQLAlchemy flask

我正在尝试使用 flask/sqlalchemy 将 json 文件插入到 postgress 数据库中,但是我 运行 插入

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

这是我的上传脚本:

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()

这是有问题的 json 文件,但我认为这不是问题,因为我可以在 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
}]}

为什么我无法上传数据有什么想法吗?

模型构造函数不接受列表,您需要单独传递每个字典:

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()