如何创建列出两个表的连接输出的FlaskAppBulider ModelView?

2024-06-16 14:54:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Flask AppBulider和SqlAlchecmy还不熟悉,我正在尝试为运行Flask appbuilder的Apache Airflow编写UI插件。 这里有两个模型代表两个表: SoundTrack (exp_track)Album (exp_album)。 SongsModelView是具有

datamodel = SQLAInterface(SoundTrack)

代码段包含三个不同文件中的三个类定义。你知道吗

这些表在数据库中创建得很好。代码段还包括DB中的表定义(这里是sqlite)。 SoundTrack模型中的列显示得很好。 但是需要从外键获取的任何列都显示为空。你知道吗

在阅读了一些内容之后,我尝试用lazy=joined在相册模型中定义一个relationship,但是exp_album.title列仍然是空的。你知道吗

经验_跟踪.py你知道吗

from airflow.models.base import Base
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow import settings

from sqlalchemy import Column, Integer, String, ForeignKey

class SoundTrack(Base, LoggingMixin):
    __tablename__ = "exp_track"

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(256), nullable=False)
    album_id = Column(Integer, ForeignKey("exp_album.id"), nullable=False)

    __table_args__ = (
        {'extend_existing': True}
    )


SoundTrack.__table__.create(settings.engine, checkfirst=True)

经验_相册.py你知道吗

from airflow.models.base import Base
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow import settings

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship

class Album(Base, LoggingMixin):
    __tablename__ = "exp_album"

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(256), nullable=False)
    artist = Column(String(256), nullable=False)

    tracks = relationship("my_songs_plugin.model.exp_track.SoundTrack", backref='track', lazy="joined")

    __table_args__ = (
        {'extend_existing': True}
    )


Album.__table__.create(settings.engine, checkfirst=True)

经验歌_视图.py你知道吗

from flask_appbuilder import ModelView
from flask_appbuilder.models.sqla.interface import SQLAInterface

from airflow.www_rbac.widgets import AirflowModelListWidget

from my_songs_plugin.model.exp_track import SoundTrack


class SongsModelView(ModelView):
    list_widget = AirflowModelListWidget
    page_size = 100

    route_base = '/songs'

    datamodel = SQLAInterface(SoundTrack)

    base_permissions = ['can_list']

    list_columns = ['id', 'title', 'album_id', 'exp_album.title']


songs_view = SongsModelView()
songs_view_data = {"category": "My Songs Plugin",
                      "name": "Songs",
                      "view": songs_view}

表定义:

CREATE TABLE exp_track (
    id INTEGER NOT NULL, 
    title VARCHAR(256) NOT NULL, 
    album_id INTEGER NOT NULL, 
    PRIMARY KEY (id), 
    FOREIGN KEY(album_id) REFERENCES exp_album (id)
);


CREATE TABLE exp_album (
    id INTEGER NOT NULL, 
    title VARCHAR(256) NOT NULL, 
    artist VARCHAR(256) NOT NULL, 
    PRIMARY KEY (id)
);

我不知道如何显示加入的列表。你知道吗


Tags: fromimportidtruealbumstringtitlenot