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.

1 Like
  • 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

did something change with the latest versions? It does not work in my case. Django says my view is not a table?

Welcome @onetoucheddy !

If this is an issue you would like assistance with, please open up a new topic for discussion.

When you do, please include the complete model definition, the DDL for the view, identification of which versions of Django and Python, what database engine, and the complete error message (with the traceback) you are getting.

Ok. Made a New topic.
Thanks,
Eddy

Verzonden vanaf Outlook voor Android