sql >> データベース >  >> RDS >> PostgreSQL

ORMでVIEWを作成するsqlalchemy

    ライブラリsqlalchemy-utilsにビューを作成する機能が含まれるようになり、ビューをsqlalchemyのメタデータに関連付けて、Base.metadata.create_allを使用してビューを作成できるようになりました。

    例:

    # installation: pip install sqlalchemy-utils
    from sqlalchemy_utils import create_view
    from sqlalchemy import select, func
    
    # engine Base & Table declaration elided for brevity
    
    stmt = select([
        TableB.id.label('table_b_id'),
        TableB.coupon_code,
        TableB.number_of_rebought_items,
        TableA.id.label('table_a_action_id'),
        TableA.time,
        TableA.parameters
    ]).select_from(TableB.__table__.outerjoin(TableA, TableB.generate_action == TableA.id))
    
    # attaches the view to the metadata using the select statement
    view = create_view('my_view', stmt, Base.metadata)
    
    # provides an ORM interface to the view
    class MyView(Base):
        __table__ = view
    
    # will create all tables & views defined with ``create_view``
    Base.metadata.create_all()
    
    # At this point running the following yields 0, as expected,
    # indicating that the view has been constructed on the server 
    engine.execute(select([func.count('*')], from_obj=MyView)).scalar() 
    



    1. Djangoで、文字列を含むのではなく、文字列の一部である用語を見つけるにはどうすればよいですか?

    2. PHP、MySQLを使用したChart.jsデータ配列。 JSON配列からデータソースを定義する方法は?

    3. MyISAMとInnoDBのインデックス使用法におけるmysqlの違い

    4. 新しいデータベースサーバーにはどのくらいのRAMが必要ですか?