Accessing MySQL Views in Django - python

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.

Related

django rest framework apis using legacy db without creating django default tables

I am going to develop django rest framework apis using postgres legacy database in which apart from the existing tables no other default django tables should be created. I would like to know without creating any django default tables or doing migrations,
can i able to access records from tables using ORM?
Can i able to access admin page without creating django auth table (i.e superuser)?
If no for both questions, only way to connect to db is using any db adapter like psycopg2?
can i able to access records from tables using ORM?
If the schema is same in your models and DB tables, then yes.
Can i able to access admin page without creating django auth table
(i.e superuser)?
As far as I can tell, no, you can't get that, unless your existing 'tables' already have that, and you have all the necessary credentials.
For question in #3, I'd use something less constraining like Flask if you have these problems.

Django not using databases from settings.py

I'm a few weeks into Python/Django and encountering an annoying problem. I have some existing databases set up in settings.py, everything looks good, I've even accessed the databases using connections[].cursor()
But the databases (and data) are not making their way into models that I want to use, despite doing the makemigrations and migrate commands. I was able to use py manage.py inspectdb --database-dbname and copied that class information manually into my models.py, but that didn't work either (typing py manage.py inspectdb on its own does not pull up these databases, I was only able to view by that --database extension). So I'm stumped, as it seems I'm doing all the right steps but not able to use these existing databases in Django.
Any other hints and steps I can take are welcome!
(Almost) all the tutorials, examples, and third-party app you'll find on the internet, and most of the Django documentation assume you use one database for your app. That's because it's fairly tricky and unusual to use multiple databases in one app.
But it's not impossible to use multiple databases and the documentation contains instructions on how to do this and what changes you'll need to make to make it work.
IMO, these are the pre-conditions to use multiple databases in one project:
The databases contain explicitly unrelated information, i.e. you won't have SQL relationships between tables in different databases. One database may contain a table with a column that maps to a column in a table in another database, but they aren't explicit (no ForeignKey or ManyToManyField in your models).
You don't need to mix databases in one query: This basically derives from the previous condition. It just means that if you need to get objects from one database that depend on the rows coming from another database, you establish the relationship in python. E.g. fetching as list of names from one database and using that list to filter a queryset on the other database.
For example, if you have an existing database that contains Strava routes (which are regularly updated via some external mechanism) and your app is a broader app that helps users getting to know their neighbourhood where they can recommend locations and things to do, being able to offer a list of routes with a starting point nearby might be something you'd want to show.
Now that you know this, the way to go is described in the doc linked above:
Create a database router so that queries for certain models are automatically routed to the correct database. E.g. Route.objects.filter(start_city=city) would automatically fetch routes from your Strava routes database.
If you need to save information about a route in your app, save it in a model in the default database and use a unique identifier of the route that will map to the strava database. Use separate queries (no relationships) to fetch information about a specific route.
That being said, if the Strava database is not regularly updated via 3rd channels and its purpose is just to pre-populate your default database, then export the data from the Strava database as json and import it into your django db using manage.py loaddata or a migration file, the latter being more flexible as to the structure of the json file.

Get column values from MongoDB table to Django

How should I create a model.py, when I already have an existing mongoDB database.
I only want to get the values from an existing Table to a the HttpResponse in Django views.py.
Is there any reference material for me to go over this?
Django internally doesn't support mongo directly and you should handle your tasks manually. (fetch data and render it yourself)
I recommend checking mongoengine which provides a django-orm like api for mongo which can be nice.
If you don't like mongoengine you can always use pymongo, the official python module for mongo

why "models.py" is not required in django when using mongodb as backend?

Recetly I've seen an app powered with django and mongodb as backend,thing is that app doesn't have a models.py file.All the datas are inserted directly in views.py.I Just need a little clarification about this particular things "Using django without models.py with mongodb."
models.py is the Django ORM way of inspecting a fixed relational schema and generating the relevant SQL code to initialize (or modify) the database. "ORM" stands for "Object-Relational Mapping".
Mongo is not relational, hence you don't need this type of schema.
(Of course, that can cause a lot of other problems if the needs of your project change later...)
But you don't need a relational schema since you're not using a relational DB.
A short answer
models.py is the ORM that comes free with django.
ORM relates your SQL schema into oopsy objects.
You can read more about ORM here-> https://en.wikipedia.org/wiki/Object-relational_mapping.
When using a noSQL, you can push objects directly into DB. So, you do not really need an ORM.
That said, whether to use it or not is a debatable part.
PS. even while using SQL, some people prefer other ORMs instead of django's built-in models.

Django models with external DBs

I have a typical Django project with one primary database where I keep all the data I need.
Suppose there is another DB somewhere with some additional information. That DB isn't directly related to my Django project so let's assume I do not even have a control under it.
The problem is that I do ont know if I need to create and maintain a model for this external DB so I could use Django's ORM. Or maybe the best solution is to use raw SQL to fetch data from external DB and then use this ifo to filter data from primary DB using ORM, or directly in views.
The solution with creating a model seems to be quite ok but the fact that DB isn't a part of my project means I am not aware of possible schema changes and looks like it's a bad practice then.
So in the end if I have some external resources like DBs that are not related to but needed for my project should I:
Try to create django models for them
Use raw SQL to get info from external DB and then use it for filtering data from the primary DB with ORM as well as using data directly in views if needed
Use raw SQL both for a primary and an external DB where they intersect in app's logic
An alternative is to use SQLAlchemy for the external database. It can use reflection to generate the SQLAlchemy-equivalent of django models during runtime.
It still won't be without issues. If your code depends on a certain column, it would still break if that column is removed or changed in an incompatible way. However, it will add a bit more flexibility to your database interactions, e.g. a Django model would definitely break if an int column is changed to a varchar column, but using database reflection, it will only break if your code depends on the fact that it is an int. If you simply display the data or something, it will remain fully functional. However, there is always a chance that a change doesn't break the system, but causes unexpected behaviour.
If, like Benjamin said, the external system has an API, that would be the preferred choice.
I suggest you to read about inspectdb and database routers. It's possible to use the django ORM to manipulate a external DB.
https://docs.djangoproject.com/en/1.7/ref/django-admin/#inspectdb
I would create the minimal django models on the external databases => those that interact with your code:
Several outcomes to this
If parts of the database you're not interested in change, it won't have an impact on your app.
If the external models your using change, you probably want to be aware of that as quickly as possible (your app is likely to break in that case too).
All the relational databases queries in your code are handled by the same ORM.

Categories