Home / Companies / Rescale / Blog / Post Details
Content Deep Dive

Using Database Views in Django ORM

Blog post from Rescale

Post Details
Company
Date Published
Author
Irwen Song
Word Count
799
Language
English
Hacker News Points
-
Summary

Incorporating database views into the Django ORM can be a beneficial strategy for querying aggregated data, as it allows data aggregation logic to be managed on the database level while retaining ORM functionality. The blog post illustrates this with an example using Django models tied to database tables for jobs, users, and charges, and then creates a database view that aggregates hardware and software charges by user, job, and month. A corresponding Django model, ChargeSummary, is mapped to this view, enabling the use of ORM queries without the ability to perform data manipulation operations like save or delete, due to the nature of views. Special considerations include specifying `on_delete=models.DO_NOTHING` for foreign keys and setting `managed=False` in the model's meta class to prevent auto migrations. The author also addresses potential migration issues when upgrading to Django 1.7 or later, offering a workaround by incorporating the view creation SQL into the initial migration file to ensure seamless deployment.