Skip to content

Instantly share code, notes, and snippets.

@brunokrebs
Created December 17, 2018 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunokrebs/57f3401ec89eaf52ead735b4591b07b5 to your computer and use it in GitHub Desktop.
Save brunokrebs/57f3401ec89eaf52ead735b4591b07b5 to your computer and use it in GitHub Desktop.
# coding=utf-8
# 1 - imports
from datetime import date
from actor import Actor
from base import Session, engine, Base
from movie import Movie
# 2 - generate database schema
Base.metadata.create_all(engine)
# 3 - create a new session
session = Session()
# 4 - fetch a movie
bourne_identity = session.query(Movie) \
.filter(Movie.title == 'The Bourne Identity') \
.first()
print(f'Just fetched the {bourne_identity.title} movie.')
# 5 - add a new actor to it
franka_potente = Actor("Franka Potente", date(1974, 7, 22))
session.add(franka_potente)
# 6 - commit and close session
session.commit()
session.close()
# 7 - list all actors
actors = session.query(Actor).all()
print('### All actors:')
for actor in actors:
print(actor.name)
print('')
@tfeathers
Copy link

This example only adds a new actor but doesn't attach her to "The Bourne Identity". Step #4 isn't needed at all. To attach her to the movie I
removed the add

session.add(franka_potente)

and then append her to the existing list of actors like this

bourne_identity.actors += [franka_potente]

Thanks for the tutorial!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment