Inserting new records with one-to-many relationship in sqlalchemy

后端 未结 2 459
半阙折子戏
半阙折子戏 2021-01-30 01:47

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):
             


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-30 02:28

    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.

    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')
    
        def __init__(self,id,name,addresses = []):
            self.id = id
            self.name = name
            self.addresses = addresses
    

    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. :)

提交回复
热议问题