1

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
1
  • show us the request you are sending Commented Jan 9, 2021 at 10:11

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.