Leveraging Database Views and Proxy Models
Explore how to leverage unmanaged database views for efficient reporting and use proxy models to create alternative admin interfaces within Django. Understand how to safely register read-only views and differentiate proxy models from abstract models to tailor your admin interface without altering the database schema.
As your application matures, the administration panel often needs to evolve beyond basic data entry. Stakeholders may request complex reporting dashboards that aggregate data across millions of rows. They may also need specialized user interfaces that present the exact same database records in completely different configurations. We fulfill these advanced requirements using unmanaged database views and Django proxy models.
Exposing database views with unmanaged models
A standard Django model maps to a standard database table. However, relational databases also support views. Views are virtual tables generated dynamically by an underlying SQL query. Database views are highly efficient for complex aggregations and reporting because they do not duplicate data.
To expose a pre-existing SQL view in the Django admin, we map a model to it using the managed = False constraint inside the model’s Meta class. This tells the migration engine of Django to completely ignore this model when creating or altering database tables.
Lines 43–44: We define the fields that match the output columns of our SQL view. Django requires a primary key, even for unmanaged views. ...