1

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.

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
Tri
  • 2,722
  • 5
  • 36
  • 65
  • You'll want to *add* those `Schedule` objects *to the session* **in the loop**. Appending data to something using a for-loop is a common source of confusion in Python in general, not specific to SQLAlchemy. – Ilja Everilä Oct 13 '19 at 08:45
  • 1
    As a hint, try and think about what assignment (the `=` operator) does, and how the loop then behaves. This is a good read on the subject: https://nedbatchelder.com/text/names.html – Ilja Everilä Oct 13 '19 at 09:25

1 Answers1

1

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()
CaffeinatedMike
  • 1,537
  • 2
  • 25
  • 57