Reputation: 3039
I have a model like this:
class Schedule(db.Model):
__tablename__ = 'schedule'
id = db.Column(db.Integer, primary_key=True)
day = db.Column(db.Enum(DayNameList, name='day'))
start_at = db.Column(db.Time())
end_at = db.Column(db.Time())
If insert one dictionary we can use this way:
time_schedule = {'day': 'Wednesday', 'end_at': '03:00', 'start_at': '02:00'}
schedule = Schedule(**time_schedule)
db.session.add(schedule)
db.session.commit()
Now I want to insert multiple dictionaries in a list. And here is the snippet of my dictionary:
list_of_dict_time_schedule = [{'day': 'Wednesday', 'end_at': '03:00', 'start_at': '02:00'}, {'day': 'Friday', 'end_at': '06:00', 'start_at': '17:01'}]
and I tried to insert it like this:
dictionary_time_schedule = {}
for data in list_of_dict_time_schedule:
for key, value in data.items():
dictionary_time_schedule[key] = value
time_schedule = Schedule(**dictionary_time_schedule)
But just the last dictionary on that looping inserted to my database, which is just:
{'day': 'Friday', 'end_at': '06:00', 'start_at': '17:01'}
So, how to insert multiple dictionary in a list to a database with Flask-SQLALchemy..?
EDIT: I also tried it like this:
for data in list_of_dict_time_schedule:
time_schedule = Schedule(day=data['day'], start_at=data['start_at'], end_at=data['end_at'])
But still same with above, just the latest dict on that looping list inserted to database.
Upvotes: 1
Views: 1082
Reputation: 1607
As stated in the comments, you need to add each new object to the session. Also, you can "autofill" your class properties using the .from_dict()
method.
schedules = [{'day': 'Wednesday', 'end_at': '03:00', 'start_at': '02:00'}, {'day': 'Friday', 'end_at': '06:00', 'start_at': '17:01'}]
for sched in schedules:
new_schedule = Schedule().from_dict(sched)
db.session.add(new_schedule)
db.session.commit()
Upvotes: 1