Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 383
wanderlust Avatar asked May 08 '13 05:05

wanderlust


Video Answer


2 Answers

You dont need to write a constructor, you can either treat the addresses property on a Person instance as a list:

a = Address(email='[email protected]') p = Person(name='foo') p.addresses.append(a) 

Or you can pass a list of addresses to the Person constructor

a = Address(email='[email protected]') p = Person(name='foo', addresses=[a]) 

In either case you can then access the addresses on your Person instance like so:

db.session.add(p) db.session.add(a) db.session.commit() print(p.addresses.count()) # 1 print(p.addresses[0]) # <Address object at 0x10c098ed0> print(p.addresses.filter_by(email='[email protected]').count()) # 1 
like image 185
DazWorrall Avatar answered Sep 28 '22 03:09

DazWorrall


I've gathered information here and elsewhere and found 3 ways to do so. In this model example (same as question):

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

1.

a = Address(email='[email protected]') p = Person(name='foo', addresses=[a]) 

2.

p = Person(name='foo') a = Address(email='[email protected]', person_id=p.id) 

3.

a = Address(email='[email protected]') p = Person(name='foo') p.addresses.append(a) 
like image 25
SIMMORSAL Avatar answered Sep 28 '22 02:09

SIMMORSAL