2017-04-10 123 views
2

我試圖創建一個Department & Ticket表之間的一對一關係。這樣,在Flask-Admin內部查看時,用戶將能夠看到名稱Department而不是ID。創建一對一的關係Flask-SQLAlchemy

我試圖建立的關係如下:

# 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名稱,而不是存儲位置?

+0

對於one-to-one請參閱http://stackoverflow.com/a/9611874/6085135 – brennan

+0

department = db.relationship('Departments',backref = backref(「tickets」,uselist = False))' uselist = False可能會修復您的視圖問題以及 – brennan

回答

4

定義函數__repr__Department

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

    def __repr__(self): 
     return self.name 

__repr__將顯示部門的名稱,而不是對象的內部表示。

PS:uselist=0是在SQLAlchemy中定義一對一關係的關鍵。

+0

優秀!那是爲我做的,謝謝! – kstullich