# Buggy code
def update(self, trakt_show, session):
    """Updates this record from the trakt media object `trakt_show` returned by the trakt api."""
    if self.id and self.id != trakt_show["ids"]["trakt"]:
        raise Exception("Tried to update db show with different show data")
    elif not self.id:
        self.id = trakt_show["ids"]["trakt"]
    self.slug = trakt_show["ids"]["slug"]
    self.imdb_id = trakt_show["ids"]["imdb"]
    self.tmdb_id = trakt_show["ids"]["tmdb"]
    self.tvrage_id = trakt_show["ids"]["tvrage"]
    self.tvdb_id = trakt_show["ids"]["tvdb"]
    if trakt_show.get("images"):
        self.images = get_db_images(trakt_show.get("images"), session)
    if trakt_show.get("airs"):
        airs = trakt_show.get("airs")
        self.air_day = airs.get("day")
        self.timezone = airs.get("timezone")
        if airs.get("time"):
            self.air_time = datetime.strptime(airs.get("time"), "%H:%M").time()
        else:
            self.air_time = None
    if trakt_show.get("first_aired"):
        self.first_aired = dateutil_parse(trakt_show.get("first_aired"), ignoretz=True)
    else:
        self.first_aired = None
    self.updated_at = dateutil_parse(trakt_show.get("updated_at"), ignoretz=True)

    for col in [
        "overview",
        "runtime",
        "rating",
        "votes",
        "language",
        "title",
        "year",
        "runtime",
        "certification",
        "network",
        "country",
        "status",
        "aired_episodes",
        "trailer",
        "homepage",
    ]:
        setattr(self, col, trakt_show.get(col))

    self.genres[:] = get_db_genres(trakt_show.get("genres") or [], session)
    self.translations[:] = get_db_trans(
        trakt_show.get("available_translations") or [], session
    )
    self.cached_at = datetime.now()


# Traceback (StaleDataError)
2016-05-18 09:50 DEBUG    api_trakt                     movie `X-Men: Apocalypse` age 0 expires in 2 days
2016-05-18 09:50 DEBUG    api_trakt                     Searching with params: tmdb=246655
2016-05-18 09:50 DEBUG    utils.requests                 Fetching https://api-v2launch.trakt.tv/search
2016-05-18 09:50 DEBUG    utils.requests                 Fetching https://api-v2launch.trakt.tv/movies/149999
--------------------------------------------------------------------------------
ERROR in app [c:\python27\lib\site-packages\flask\app.py:1423]:
Exception on /trakt/movies/X-Men: Apocalypse/ [GET]
--------------------------------------------------------------------------------
Traceback (most recent call last):
File "c:\python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "c:\python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\python27\lib\site-packages\flask_restful\__init__.py", line 477, in wrapper
resp = resource(*args, **kwargs)
File "c:\python27\lib\site-packages\flask\views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "c:\python27\lib\site-packages\flask_restplus\resource.py", line 42, in dispatch_request
resp = meth(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\utils\database.py", line 34, in wrapper
return func(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\utils\sqlalchemy_utils.py", line 141, in __exit__
self.commit()
File "c:\python27\lib\site-packages\sqlalchemy\orm\session.py", line 801, in commit
self.transaction.commit()
File "c:\python27\lib\site-packages\sqlalchemy\orm\session.py", line 392, in commit
self._prepare_impl()
File "c:\python27\lib\site-packages\sqlalchemy\orm\session.py", line 372, in _prepare_impl
self.session.flush()
File "c:\python27\lib\site-packages\sqlalchemy\orm\session.py", line 2019, in flush
self._flush(objects)
File "c:\python27\lib\site-packages\sqlalchemy\orm\session.py", line 2137, in _flush
transaction.rollback(_capture_exception=True)
File "c:\python27\lib\site-packages\sqlalchemy\util\langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "c:\python27\lib\site-packages\sqlalchemy\orm\session.py", line 2101, in _flush
flush_context.execute()
File "c:\python27\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 373, in execute
rec.execute(self)
File "c:\python27\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 487, in execute
self.dependency_processor.process_saves(uow, states)
File "c:\python27\lib\site-packages\sqlalchemy\orm\dependency.py", line 1092, in process_saves
secondary_update, secondary_delete)
File "c:\python27\lib\site-packages\sqlalchemy\orm\dependency.py", line 1113, in _run_crud
result.rowcount)
StaleDataError: DELETE statement on table 'trakt_image_movie' expected to delete 1 row(s); Only 2 were matched.

# Fixed code
def update(self, trakt_show, session):
    """Updates this record from the trakt media object `trakt_show` returned by the trakt api."""
    if self.id and self.id != trakt_show["ids"]["trakt"]:
        raise Exception("Tried to update db show with different show data")
    elif not self.id:
        self.id = trakt_show["ids"]["trakt"]
    self.slug = trakt_show["ids"]["slug"]
    self.imdb_id = trakt_show["ids"]["imdb"]
    self.tmdb_id = trakt_show["ids"]["tmdb"]
    self.tvrage_id = trakt_show["ids"]["tvrage"]
    self.tvdb_id = trakt_show["ids"]["tvdb"]
    if trakt_show.get("images"):
        set_image_attributes(self, trakt_show)
    if trakt_show.get("airs"):
        airs = trakt_show.get("airs")
        self.air_day = airs.get("day")
        self.timezone = airs.get("timezone")
        if airs.get("time"):
            self.air_time = datetime.strptime(airs.get("time"), "%H:%M").time()
        else:
            self.air_time = None
    if trakt_show.get("first_aired"):
        self.first_aired = dateutil_parse(trakt_show.get("first_aired"), ignoretz=True)
    else:
        self.first_aired = None
    self.updated_at = dateutil_parse(trakt_show.get("updated_at"), ignoretz=True)

    for col in [
        "overview",
        "runtime",
        "rating",
        "votes",
        "language",
        "title",
        "year",
        "runtime",
        "certification",
        "network",
        "country",
        "status",
        "aired_episodes",
        "trailer",
        "homepage",
    ]:
        setattr(self, col, trakt_show.get(col))

    self.genres = [
        TraktGenre(name=g.replace(" ", "-")) for g in trakt_show.get("genres", [])
    ]
    self.cached_at = datetime.now()
    self.translation_languages = trakt_show.get("available_translations", [])