Prevent duplicate table entries in a many-to-many relationship in SQLAlchemy

后端 未结 1 1083
时光取名叫无心
时光取名叫无心 2020-12-21 15:40

I am trying to set up a movie database using SQLAlchemy with a many-to-many relationship. I have two tables, \'movie\' and \'actor\', and an association table \'movie_actor\

1条回答
  •  生来不讨喜
    2020-12-21 16:07

    You'll likely need to insert a self.session.begin_nested() in your try: block. Then if you need to rollback because of the duplicate key, you can still add the actors to the movie:

    from sqlalchemy.exc import IntegrityError  # only catch the right exception!
               # in for loop:
                    try:
                            session.begin_nested()
                            actor = Actor(actors[i])
                    except IntegrityError:
                            print "Duplicate Actor"
                            self.session.rollback() # subtransaction
                            actor = self.session.query(Actor).\
                               filter(Actor.name==actors[i]).first()
                    else:
                            self.session.commit()  # subtransaction
    
                    # add the appropriate association between the movie and the actors to the MovieActor table
                    movie.movie_actor.append(MovieActor(actor))
                    # add the new actor and movieactor association to the session
                    self.session.add(movie)
                    self.session.commit()
    

    Edit: always except IntegrityError when expecting duplicate key errors.

    0 讨论(0)
提交回复
热议问题