-1

We are migrating our intranet application and have decided to choose the Django framework. We control all of our database via source control and managed scripts, so we do not use the migrate feature to create tables for us. Views and Tables can change, all business logic is held in the database.

I want to make Django API endpoint which is basically select * from my_table_or_view; and Django can return a JSON response with the column names and values. Some database tables have close to 100 columns each so I don't want to write out each and every field name and type just to return a query. What happens if we add another column to the view - will I have to update it in Django as well? What if I change the column type - will my application fail as well?

The frontend is written in VueJS - it makes a request to the API endpoint and should use the columns selected in the frontend, obviously if I remove a column it will break but I don't want to have to add the column in the django framework even if it is not used.

I've read the raw SQL queries section of the docs but i'm not sure where this applies to. Does this logic sit in the views section?

I've tried directing a URL endpoint in URLS.py to a custom class in views.py but not sure this is correct, does this logic need to be in a serializer?

I'd like the simplest method possible, potentially not using models, just raw SQL is fine.

rup
  • 483
  • 5
  • 15
  • Thats an awful lot of questions, narrative, and unnecessary background. What is the smallest way to state this question? Do you want to just select * from a table and resturn it from an endpoint? If you just want an API over your database you can use something like https://github.com/PostgREST/postgrest, but judging from your question you are probably on mysql. – Andrew Mar 30 '21 at 15:36

1 Answers1

0

One option for you is to sync your db to django models every time you change your schema and then use it normally, both ORM and raw SQL queries would be possible.

There's a function called inspectdb that does that natively, here is a reference to it https://docs.djangoproject.com/en/3.1/ref/django-admin/#inspectdb

  • 1
    I am aware of the inspectdb function but I still do not want thousands of lines of column definitions in my django models code - do I *really* need to declare the models? Can I just write raw SQL instead? – rup Mar 30 '21 at 13:20
  • You could use a direct connection library: https://stackoverflow.com/questions/5931586/raw-sql-queries-in-django-views – Vitor Ramalho Mar 30 '21 at 16:25