Flask Admin:将相关对象的属性添加到模型视图中的列列表中

时间:2018-08-13 10:19:31

标签: flask flask-admin

我有以下数据库模型:

class Sentence(db.Model):
    __tablename__ = 'sentences'
    sentence_id = db.Column(db.Integer, primary_key=True)                                        
    sentence_text = db.Column(db.String(1024), unique=False, nullable=False)
    records = db.relationship('Record', backref='sentence', lazy='dynamic')
    def __repr__(self):
        return '<Sentence id=%r>' % (self.sentence_id)


class Record(db.Model):
    __tablename__ = 'records'
    record_id = db.Column(db.Integer, primary_key=True)                                                
    sentence_id = db.Column(db.Integer, db.ForeignKey('sentences.sentence_id'), nullable=False)

在我的flask-admin后端中,我想在记录视图中显示句子文本。

我创建了一个自定义模型视图:

class RecordView(sqla.ModelView):
    column_list = ('record_id', 'sentence', 'sentence_text',)

但是,不显示句子文本。

enter image description here

我将如何实现?

1 个答案:

答案 0 :(得分:0)

您需要在模型中添加合适的字符串表示形式。 Flask-Admin会将其用于输出。

例如Python 2

class Sentence(db.Model):
    __tablename__ = 'sentences'
    sentence_id = db.Column(db.Integer, primary_key=True)
    sentence_text = db.Column(db.String(1024), unique=False, nullable=False)
    records = db.relationship('Record', backref='sentence', lazy='dynamic') 

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return self.sentence_text

Python 3

class Sentence(db.Model):
    __tablename__ = 'sentences'
    sentence_id = db.Column(db.Integer, primary_key=True)
    sentence_text = db.Column(db.String(1024), unique=False, nullable=False)
    records = db.relationship('Record', backref='sentence', lazy='dynamic') 

    def __str__(self):
        return self.sentence_text

要引用相关对象的属性,请使用虚线路径:

class RecordView(sqla.ModelView):
    column_list = ('record_id', 'sentence', 'sentence.sentence_text')