Setting Up a Postgres Database View with a Django Model

I am looking to optimize an application, and one of the options that I am looking at is creating a virtual table that will allow me to reduce the number of queries made to the database. I am currently using prefetch_related and select_related to join on a reverse of a foreignkey and for multiple other foreignkeys on the model. I want to see if I can further reduce the number slightly by accessing a virtual view. I came across little documentation on this (though I may just not know what to be looking for).

I was able to find this article: Using Database Views in Django ORM - Rescale. And I also found this package: django-database-view · PyPI, but it looks like it has not been updated in the past two years. I know this will likely increase only increase performance marginally, but I am curious about how to do this specifically using Django and Postgres. Any help is appreciated.

  • Create a model to represent your database view:
class MyDBView(models.Model):
    something = models.CharField(max_length=100)

    class Meta:
        db_table = "name_of_your_view_here"
        managed = False  # Instructs Django to ignore this during database migrations

Next, you can set up the database view using one of two methods:

1 Like

As mentioned in the prior response, it’s really not that big of a deal. I don’t even think a package for it is particularly necessary.

From the perspective of Django, a view would just be another table. (You do want to make sure it’s configured as managed = False.) Once you’ve defined the view and the corresponding model, you can use it in queries like any other model. (Whether you can update any data is a different question - but using it for queries only shouldn’t create any problems at all.)

This is something that we have done in a number of “data-migration” situations, where we have created views to facilitate data transformations from one system to another.

1 Like

Thank you so much this worked for me