I'm following the flask-sqlalchemy tutorial on declaring models regarding one-to-many relationship. The example code is as follows:
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
addresses = db.relationship('Address', backref='person',
lazy='dynamic')
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
person_id = db.Column(db.Integer, db.ForeignKey('person.id'))
Now I'm wondering how to insert new records into DB using such model. I assume I need a constructor init, but I have difficulties to understand how it should be implemented and used. The main problem for me here is that Person depends on Address and Address has ForeignKey to Person, so it should know about the Person in advance.
Plase help me to understand how it should be performed.
Thank you in advance.
In some cases there is have an Exception like "list object has no attribute _sa_instance_state".
Solve this exception.
The most important thing while looking into this model is to understand the fact that this model has a one to many relationship, i.e. one Person has more than one address and we will store those addresses in a list in our case.
So, the Person class with its init will look something like this.
So this Person class will be expecting an id, a name and a list that contains objects of type Address. I have kept that the default value to be an empty list.
Hope it helps. :)
You dont need to write a constructor, you can either treat the
addresses
property on aPerson
instance as a list:Or you can pass a list of addresses to the
Person
constructorIn either case you can then access the addresses on your
Person
instance like so: