0

How can I access a MySQL view in Django?

I find it hard to believe that I am the first to want to do this with Django, but because both Django and MySQL use the term 'view' the search results have not been helpful. I have read the Django documentation on running raw SQL queries and accessing stored procedures, but it doesn't quite solve my particular need.

Basically, there are several MySQL views in the database that I need to manage/access via Django like I can with tables. I realize that I can access views by running raw SQL queries in Django, but I value the control Django models and migrations provide and would like to be able to do the same with views.

Ideally, I would like the official Django way of doing this but if that doesn't exist I would also value your hacks/workarounds for this.

Rekamanon
  • 217
  • 2
  • 10
  • Create a matching model, set the [model option](https://docs.djangoproject.com/en/3.0/ref/models/options/) `managed=False` and make sure to adapt other things like the table name. – Klaus D. Jul 15 '20 at 14:12
  • 1
    Does this answer your question? [Create database view from django model](https://stackoverflow.com/questions/51817841/create-database-view-from-django-model) – Tom Carrick Jul 15 '20 at 14:25
  • @KlausD. could you elaborate on that? The documentation makes it sound like it is the same implementation as a model other than this flag, but doesn't clarify how I would map the fields of this unmanaged model to the columns of a separate table that is managed. – Rekamanon Jul 16 '20 at 12:28
  • TomCarrick the accepted answer does look like it may work, but I'd prefer a solution not requiring 3rd-party plugins. However, the unaccepted answer looks more promising to me and may have actually just clarified what I wasn't understanding about @KlausD.'s comment. – Rekamanon Jul 16 '20 at 12:33

0 Answers0