我有一个烧瓶项目,我开始学习烧瓶管理模块。
所需表的SqlAlchemy架构。
import datetime
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, relationship
Base = declarative_base()
class Workgroup(Base):
__tablename__ = 'workgroups'
id = sqlalchemy.Column(sqlalchemy.Integer,
primary_key=True,
autoincrement=True
)
name = sqlalchemy.Column(sqlalchemy.String(16))
shorthand = sqlalchemy.Column(sqlalchemy.String(4))
def __unicode__(self):
return self.name
class Drive(Base):
"""
A drive in an edit station.
"""
__tablename__ = 'drives'
id = sqlalchemy.Column(sqlalchemy.Integer,
primary_key=True,
autoincrement=True
)
name = sqlalchemy.Column(sqlalchemy.String(64))
computer_id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey(Computer.id)
)
computer = relationship('Computer', backref='drives')
is_active = sqlalchemy.Column(sqlalchemy.Boolean)
free_space = sqlalchemy.Column(sqlalchemy.BigInteger)
used_space = sqlalchemy.Column(sqlalchemy.BigInteger)
total_space = sqlalchemy.Column(sqlalchemy.BigInteger)
percentage_full = sqlalchemy.Column(sqlalchemy.Float)
boot_time = sqlalchemy.Column(sqlalchemy.DateTime)
last_changed_workgroup = sqlalchemy.Column(sqlalchemy.DateTime)
last_checked_in = sqlalchemy.Column(sqlalchemy.DateTime)
last_notified = sqlalchemy.Column(sqlalchemy.DateTime)
image_version = sqlalchemy.Column(sqlalchemy.String(64))
image_date = sqlalchemy.Column(sqlalchemy.DateTime)
current_workgroup_id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey(Workgroup.id)
)
workgroup = relationship('Workgroup', backref='drives')
class DriveAdmin(sqla.ModelView):
column_display_pk = True
column_hide_backrefs = False
column_display_all_relations = True
form_columns = [ 'computer_id', 'workgroup.name', ]
column_list = ('computer.name', 'name', 'workgroup', 'computer.short_description', 'computer.notes',
'computer.station_type.description', 'computer.room.name')
class WorkgroupAdmin(sqla.ModelView):
column_display_pk = True # optional, but I like to see the IDs in the list
column_hide_backrefs = False
column_list = ('id', 'name', 'shorthand')
# Create admin
admin = admin.Admin(app, name='Example: SQLAlchemy2', template_mode='bootstrap3')
admin.add_view(WorkgroupAdmin(schema.Workgroup, db))
admin.add_view(DriveAdmin(schema.Drive, db))
将'workgroup'的表格列替换为'workgroup.name'会给我一个无效的模型属性名称,即使我已经在代码中的其他地方成功使用了schema.workgroup.name。
如何让workgroup.name值显示而不是对象表示?
感谢阅读!
答案 0 :(得分:5)
您需要让工作组类通过 repr 函数返回其名称。这将在现场展示。
class Workgroup(Base):
__tablename__ = 'workgroups'
id = sqlalchemy.Column(sqlalchemy.Integer,
primary_key=True,
autoincrement=True
)
name = sqlalchemy.Column(sqlalchemy.String(16))
shorthand = sqlalchemy.Column(sqlalchemy.String(4))
def __unicode__(self):
return self.name
def __repr__(self):
return '<Workgroup %r>' % (self.name)