Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - how to insert multiple rows into a single table using flask-sqlalchemy

Here this is my table.

class relatives(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    main_id = db.Column(db.Integer, db.ForeignKey('maindevotee.id'), nullable=False)
    name = db.Column(db.String(225))
    star = db.Column(db.String(225))
    gender = db.Column(db.String(45))
    relation = db.Column(db.String(45))

    def json(self):
        return {'main_id': self.main_id, 'name': self.name, 'star':self.star,
                'gender': self.gender, 'relation': self.relation}
    def add_relatives(_main_id, _name, _star, _gender, _relation):
        new_relative = relatives(main_id=_main_id, name=_name, star=_star, gender=_gender,
                                 relation=_relation)
        db.session.add(new_relative)
        db.session.commit()

I am unable to insert multiple rows(multiple objects) in a table.How it is possible. I mean i want to add more than one row in a single request.

@app.route('/relatives',methods=['GET','POST'])
def relative():
    request_data = request.get_json()
    relatives.add_relatives(request_data['main_id'], request_data['name'], request_data['star'],
                            request_data['gender'], request_data['relation'])
    response = Response('Relative added', 201, mimetype='application/json')
    return response
question from:https://stackoverflow.com/questions/65641380/how-to-insert-multiple-rows-into-a-single-table-using-flask-sqlalchemy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have two ways of doing this:

data = [{"main_id": 1, "name": "test", ...}, ...]

# method 1
relatives_to_add = [Relative(**row) for row in data]
db.session.add_all(relatives_to_add)
db.session.commit()

# method 2
db.session.bulk_insert_mappings(Relative, data)
db.session.commit()

PS: use proper casing for classes https://www.python.org/dev/peps/pep-0008/#class-names


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...