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.

2
  • 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. Commented Oct 13, 2019 at 8: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: nedbatchelder.com/text/names.html Commented Oct 13, 2019 at 9:25

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.