Django and Oracle database (accessing your views via ORM)

Asked

Viewed 467 times

2

Hello, despite the title self explanatory. I will detail my doubt to follow.

I have a pre-existing Oracle database, integrated it with Django by configuring the default connection in Settings and running the command Manage.py inspectdb > _models.py. Thus creating a file with several mapped classes from my database.

My question is: Such a database has views, predefined sql routines that return me a very useful data selection. I would like to know how to use them within Django, because they are not mapped natively and my lay understanding of database and Orm leave me without many choices other than trying to rewrite their logics in pure sql.

Sorry if the answer is simple and thank you for your support in advance.

  • I saw something here about the class Meta : https://blog.rescale.com/using-database-views-in-django-orm/ I hope it will be useful =]

  • If you have problems with English, say that I try to translate the relevant points

1 answer

2


I would like to openly thank Jefferson Quesado for sharing a link with the ideal logic, having just had to adapt to my development environment.

Really, DataBase Views are common database tables, with their values generated dynamically during your query, function as select And they don’t take up space in the database, even though they’re persistent. My low understanding of this hampered in the creative search for a solution.

The detail really came from the fact of being persistent, are then considered real tables of the database and so, can also be mapped.

I created a class in my _models.py with the exact name of my Oracle database View in question, following the standard scope of a class representing a relational object. I inherited it from models.Model, I added its attributes with the exact names and properties of the view fields that I intended to map (if you have questions about which properties to assign, take a look at the SQL of your table and see the properties of the fields that it references, including a very important detail, the Primary/Foreign Keys for your view model are actually the Keys of the tables that your abstract view, even if it seems unnecessary, would like to leave this detail with its due prominence here, since in the view scope there are no references to primary keys/secondary, but make no mistake and attribute primary_key=True fields. Otherwise Django will raise an unknown ID exception when making any QuerySet and then nothing done. Haha).

Finally, the class Meta within of the model class of your data base view. Referencing your view as a real table (after all it in the entrails is).

class Meta:
    managed = False
    db_table = 'nome_da_sua_view'

I recommend a visit to link left by Jefferson Quesado, worth checking out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.