alphanumeric alphanumeric - 19 days ago 5
Python Question

How to query multiple items using Flask SQLAlchemy

After importing the modules:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


and declaring
app
and
db
objects:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)


I go ahead and create two tables:
User
and
Email
:

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
addresses = db.relationship('Email', backref='person', lazy='dynamic')

class Email(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
person_id = db.Column(db.Integer, db.ForeignKey('user.id'))


With
db.relationship
in place I can now link some multiple emails to the same
user
. First I create two email addresses:

first_email = Email(email='first@email.com')
second_email = Email(email='second@email.com')


Then I am passing these two emails to
User
class at the time it is being created:

user = User(name='User Name', addresses = [first_email, second_email])


To see which user is linked to which email I can simply use:

print first_email.person
print user.addresses.all()


Now I want to add another third email to the same
user
. How do I append a new email to the list of the emails that have been already linked to the
user
?

Answer
new_email = Email(email='new_email@example.com')
user.addresses.append(new_email)
db.session.commit()

This will append the email address to the relationship.