创建一对一的关系Flask-SQLAlchemy

时间:2017-04-10 20:39:02

标签: python python-3.x flask flask-sqlalchemy flask-admin

我正在尝试在Department&之间建立一对一的关系。 Ticket表。这样,当查看Flask-Admin内部时,用户将能够看到Department名称而不是ID。

我尝试按如下方式设置关系:

# Ticket Table
class Tickets(db.Model):
    __tablename__ = 'tickets'

    ticketID = db.Column(db.Integer, nullable=False, primary_key=True, autoincrement=True, unique=True)
    cust_name = db.Column(db.String(50), nullable=False)
    cust_email = db.Column(db.String(50), nullable=False)
    cust_phone = db.Column(db.Integer, nullable=False)
    tix_dept = db.Column(db.Integer, db.ForeignKey('department.deptID'))
    tix_severity = db.Column(db.Integer, nullable=False)
    tix_msg = db.Column(db.String(500), nullable=False)
    tix_status = db.Column(db.String(10), nullable=False)
    tix_recv_date = db.Column(db.String(20), nullable=False)
    tix_recv_time = db.Column(db.Integer, nullable=False)

    # define relationship
    department = db.relationship('Departments')


# Department Table
class Departments(db.Model):
    __tablename__ = 'department'

    deptID = db.Column(db.Integer, primary_key=True, autoincrement=True, unique=True)
    dept_name = db.Column(db.String(40), nullable=False)
    dept_empl = db.Column(db.String(40), nullable=False)
    dept_empl_phone = db.Column(db.Integer, nullable=False)

然后我的Flask-Admin次观看次数为:

admin.add_view(TicketAdminView(Tickets, db.session, menu_icon_type='glyph', menu_icon_value='glyphicon-home'))
admin.add_view(DepartmentAdminView(Departments, db.session))

故障单管理面板:

Department Admin View

单一故障单编辑: Department Dropdown

如何显示Department名称而不是内存位置?

1 个答案:

答案 0 :(得分:4)

定义__repr__的函数Department

class Department(db.Model)
    # ... column definition

    def __repr__(self):
        return self.name

__repr__将显示部门的名称,而不是对象的内部表示。

PS:uselist=0是在SQLAlchemy中定义一对一关系的关键。