Fastest way to insert object if it doesn't exist with SQLAlchemy

后端 未结 1 919
囚心锁ツ
囚心锁ツ 2021-01-01 03:47

So I\'m quite new to SQLAlchemy.

I have a model Showing which has about 10,000 rows in the table. Here is the class:

class Showing(Base):
    __tab         


        
相关标签:
1条回答
  • 2021-01-01 04:30

    If any such object is unique based on a combination of columns, you need to mark these as a composite primary key. Add the primary_key=True keyword parameter to each of these columns, dropping your id column altogether:

    class Showing(Base):
        __tablename__   = "showings"
    
        time            = Column(DateTime, primary_key=True)
        link            = Column(String)
        film_id         = Column(Integer, ForeignKey('films.id'), primary_key=True)
        cinema_id       = Column(Integer, ForeignKey('cinemas.id'), primary_key=True)
    

    That way your database can handle these rows more efficiently (no need for an incrementing column), and SQLAlchemy now automatically knows if two instances of Showing are the same thing.

    I believe you can then just merge your new Showing back into the session:

    def AddShowings(self, showing_times, cinema, film):
        for showing_time in showing_times:
            self.session.merge(
                Showing(time=showing_time[0], link=showing_time[1],
                        film=film, cinema=cinema)
            )
    
    0 讨论(0)
提交回复
热议问题