Efficiently updating database using SQLAlchemy ORM

前端 未结 6 1374
梦毁少年i
梦毁少年i 2020-11-28 01:14

I\'m starting a new application and looking at using an ORM -- in particular, SQLAlchemy.

Say I\'ve got a column \'foo\' in my database and I want to increment it.

6条回答
  •  遥遥无期
    2020-11-28 01:36

    Here's an example of how to solve the same problem without having to map the fields manually:

    from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine
    from sqlalchemy.exc import IntegrityError
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.orm.attributes import InstrumentedAttribute
    
    engine = create_engine('postgres://postgres@localhost:5432/database')
    session = sessionmaker()
    session.configure(bind=engine)
    
    Base = declarative_base()
    
    
    class Media(Base):
      __tablename__ = 'media'
      id = Column(Integer, primary_key=True)
      title = Column(String, nullable=False)
      slug = Column(String, nullable=False)
      type = Column(String, nullable=False)
    
      def update(self):
        s = session()
        mapped_values = {}
        for item in Media.__dict__.iteritems():
          field_name = item[0]
          field_type = item[1]
          is_column = isinstance(field_type, InstrumentedAttribute)
          if is_column:
            mapped_values[field_name] = getattr(self, field_name)
    
        s.query(Media).filter(Media.id == self.id).update(mapped_values)
        s.commit()
    

    So to update a Media instance, you can do something like this:

    media = Media(id=123, title="Titular Line", slug="titular-line", type="movie")
    media.update()
    

提交回复
热议问题