0

This is my first use of flask-appbuilder, and the question seems to me quite basic. Sorry if it is trivial, but my research did not allow me to find useful information. Anyway.

I would like to allow the user to navigate through the data by following the foreign keys, simply by clicking on them to jump to the referenced element of another table.

Example: Two tables: Users and Departments with primary keys UserId and DepartementId. The User table has a foreign key DepartementId which references the Department table (intuitively: the department to which the user belongs). When displaying the list of users or one single user (Users/Show), I would like the foreign key DepartementId to be a clickable hyperlink bringing the user directly to the display of the department of the user.

I can't put any code example, just because I don't have the beginning of a track… 

Any help is welcome. I’m sticked !

1 Answers1

0

Ok. I found the trick.

Here it is. Still with our two tables Users and Departments.

In the UsersModel, after declaring the foreign key:

class UsersModel(Model):
    …
    DepartmentID = Column(Integer, ForeignKey('Departments.DepartmentId'))
    Department = relationship('DepartmentsModel')
    …

just add an extra field making use of these two.

    def DepartmentHTML(self):
        return Markup('<a href="/departmentsmodelview/show/'+str(self.DepartmentID)+'">'+str(self.Department)+'</a>')

Now, in the UsersModelView:

class UsersModelView(ModelView):
    label_columns = {…'DepartmentHTML':'Department'…}
    list_columns = […'UserId','DepartmentHTML'…]
    add_columns = […'UserId','Department'…]
    edit_columns = […'UserId','Department'…]
    show_columns = […'UserId','DepartmentHTML'…]

It's as simple.

I was convinced that making foreign keys clickable is part of the framework job, and I was uncomfortable with the idea of including html code in the Model…

Now, if someone has some idea about how to do the same for the reverse foreign keys, it's my next step and it sounds to be another piece of cake.