如何设置一个额外的字段的列表视图中的价值?(How to set the value of an e

2019-10-24 11:39发布

我增加了一个额外的字段clanModelView类的Matriline并将其添加到列表视图中的列,如下图所示。

如何设置额外的字段的值clan列表视图?

views.py

class MatrilineAdmin(sqla.ModelView):

    form_extra_fields = {
        'clan': SelectField('Clan',
            coerce=int,
            choices=[ (c.id, c.name) for c in Clan.query.all()])
    }
    create_template = 'admin/create.html'
    edit_template = 'admin/edit.html'
    column_list = ('name', 'pod', 'clan')

models.py

class Matriline(db.Model):
    __tablename__ = 'matriline'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))
    calls = db.relationship('Call', backref='matriline', lazy='select')
    pod_id = db.Column(db.Integer, db.ForeignKey('pod.id'))

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name


class Pod(db.Model):
    __tablename__ = 'pod'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))
    matrilines = db.relationship('Matriline', backref='pod', lazy='select')
    clan_id = db.Column(db.Integer, db.ForeignKey('clan.id'))

    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name


class Clan(db.Model):
    __tablename__ = 'clan'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))
    pods = db.relationship('Pod', backref='clan', lazy='select')

    def __unicode__(self):
        return self.name

Answer 1:

根据代码BaseModelView.index_view存在这个问题并没有“配置”选项。 您将需要重写get_list方法在MatrilineAdmin -class。

这看起来是这样的:

class MadrilineAdmin(sqla.ModelView):
    def get_list(self, *args, **kwargs):
        count, data = super().get_list(*args, **kwargs)
        for d in data:
            d.clan = 'whatever you want'
        return count, data

您也可以尝试到指定的关系 ,从母系氏族和氏族财产直接在模型类中定义:

class Matriline(db.Model):
    # …
    pod = db.relationship('Pod')

    @property
    def clan(self):
        if not self.pod:
            return None
        return self.pod.clan

class Pod(db.Model):
    # …
    clan = db.relationship('Clan')


Answer 2:

class ExampleDatabase(sqla.ModelView):

    def _list_name(self, context, model, name):
        return 'something you like'

    column_formatters = {
        'example': _list_name
    }

    def get_column_names(self, only_columns, excluded_columns):
        only_columns.append('example')
        return super().get_column_names(only_columns, excluded_columns)

我的作品。



文章来源: How to set the value of an extra field in the list view?