Python Forum
Inserting multiple rows in a single request. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Inserting multiple rows in a single request. (/thread-31907.html)



Inserting multiple rows in a single request. - swaroop - Jan-09-2021

How to insert multiple rows in a single request using flask-sqlalchemy.
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



RE: Inserting multiple rows in a single request. - robsuttonjr - Jan-09-2021

I am thinking you need to pass a list then iterate over the list.


RE: Inserting multiple rows in a single request. - swaroop - Jan-11-2021

(Jan-09-2021, 09:06 PM)robsuttonjr Wrote: I am thinking you need to pass a list then iterate over the list.

Can you please send me the correct code.