amertkara
amertkara

Reputation: 1379

Sqlalchemy One-to-Many Insert

I have a dictionary and a list (of dictionaries) variables that I parsed some data into and these two variables have one-to-many relation between each other. I wonder if there is any way to put these dictionaries into table classes and store them into the database. I expect sqlalchemy to handle the foreign key details. Also Dictionaries have lots of keys so it should populate the object fields from dictionary.

Upvotes: 1

Views: 1029

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55293

There are two steps involved in creating a Many To One relationship in SQLAlchemy:

  1. Create the constraint on the Dependent object. This will ensure that Dependents only reference valid Masters. For this, you will need a Primary Key on the Master object.
  2. Create a reference so you can access the Master in an Object-Oriented fashion from the Dependent.

A note: don't get confused. The SQLAlchemy documentation uses an example where the relationship is Parents (n) -> Child (1). To avoid confusion, I used the wording Dependent (n) -> Master (1).

Upvotes: 2

Related Questions