Skip to content

Tedious per page code

valhuber edited this page Aug 12, 2020 · 1 revision

FAB requires that we edit 2 key files to make our "empty" project interact with the database, as described below. These can get tedious, since you must do this for each table / page.

models.py module - describes each table

The models.py module describes your database tables, for sqlalchemy (Python ORM). The file contains segments like this for each table:

class OrderDetail(BaseMixin, Model):
    __tablename__ = 'OrderDetail'

    Id = Column(String(8000), primary_key=True)
    OrderId = Column(Integer, ForeignKey("Order.Id"), nullable=False)
    Order = relationship("Order")
    ProductId = Column(Integer, ForeignKey("Product.Id"), nullable=False)
    Product = relationship("Product")
    UnitPrice = Column(DECIMAL, nullable=False)
    Quantity = Column(Integer, nullable=False)
    Discount = Column(Float, nullable=False)

Note the ForeignKey / relationship code. To get multi-table pages, either add such code to the models.py file, or (better) add foreign keys to your database.

views.py module - describes each page

The views.py module is used by fab to generate pages. It consists of segments like this for each page:

class OrderModelView(ModelView):
   datamodel = SQLAInterface(Order)
   list_columns = ["ShipName", "Customer.CompanyName", ... "EmployeeId", "CustomerId"]
   show_columns = ["ShipName", "Customer.CompanyName", "OrderDate", ... "ShipCountry", "Id", "EmployeeId", "CustomerId"]
   edit_columns = ["ShipName", "OrderDate",... "ShipCountry", "Id", "EmployeeId", "CustomerId"]
   add_columns = ["ShipName", "OrderDate", ... "ShipCountry", "Id", "EmployeeId", "CustomerId"]
   related_views = [OrderDetailModelView]

appbuilder.add_view(
      OrderModelView, "Order List", icon="fa-folder-open-o", category="Menu")

Solution: Generators

There are solutions for both:

  • You can build models.py with tools like sqlacodegen.
  • You can build views.py with the FAB Quickstart Utility

The FAB Quick Start Guide shows how.