Flask and SQLAlchemy sort in display without new query? - python

I'm displaying the results from an SQLAlchemy (Flask-SQLAlchemy) query on a particular view. However the sorting/order is only set by what I originally passed into the query ( order_by(desc(SelectedTable.date_changed)) ). I'm trying to now add functionality that each column that is displayed can be selected to order the presentation.
Is there a way to alter the way a returned query object is sorted once it's returned to create this behavior? Or will I need to build custom queries for each possible column that could be sorted by and ascending/descending?
Is there a recipe for implementing something like this? I've tried google, here, the Flask, Flask-SQLAlchemy, and SQLAlchemy docs for something along these lines but haven't seen anything that touches on the subject and beginning to think that I'm going to need to use custom queries or without new queries try some JavaScript in the Jinja Template to achieve this.
Thanks!

Related

Insert statment created by django ORM at bulk_create

I am kind of new to python and django.
I am using bulk_create to insert a lot of rows and as a former DBA I would very much like to see what insert statments are being executed. I know that for querys you can use .query but for insert statments I can't find a command.
Is there something I'm missing or is there no easy way to see it? (A regular print is fine by me.)
The easiest way is to set DEBUG = True and check connection.queries after executing the query. This stores the raw queries and the time each query takes.
from django.db import connection
MyModel.objects.bulk_create(...)
print(connection.queries[-1]['sql'])
There's more information in the docs.
A great tool to make this information easily accessible is the django-debug-toolbar.

Accessing all columns from MySQL table using flask sqlalchemy

I'm trying to get the columns for a MySQL table whether in a string or a list format.
Since I defined the table through my main app, I could use dir(table_name) to get a list of attributes but those contain private attributes and other built-in attributes like "query" or "query_class". Filtering these would be possible but I'm trying to find an easier way to get the columns without going through the attribute route.
Between reading the flask-sqlalchemy documentation and sqlalchemy documentation, I noticed that using table_name.c will work for sqlalchelmy. Is there an equivalent for flask-sqlalchemy?
Flask-SQLAlchemy does nothing to the SQLAlchemy side of things, it is just a wrapper to make it easier to use with Flask along with some convenience features. You can inspect orm objects the same way you normally would. For example, inspecting a model returns its mapper.
m = db.inspect(MyModel)
# all orm attributes
print(list(m.all_orm_descriptors.keys()))
# just the columns
print(list(m.columns.keys()))
# etc.

Saving datas from one database to another

I want to copy the datas from one database to another in Postgres. I wrote a script in django and was able to grab a datas from one specific table but how can i add that data in other database.New database has same table and column name, i want to save that old database files to new database.
This might be easy for some of you guys but i really couldnt figure that out.
I'm not familiar with either API but if the rows/columns have the same dimmensions you could do something like (and this is partially pseudocode):
for x in range(height):
for y in range(width):
data = call_data_from_database_A(x, y)
new_entry = enter_data_into_database_B(x, y)
Where the Call_data is you're getting data from that specific row/column, and enter_data enters the data into that specific row/column. I'm not familiar with either API but if you find the two I'm sure you could figure it out rather quickly.
Instead of writing your own import and export code, why not use the native capabilities of Postgres and dump the table from your old database then import it into your new one:
http://www.postgresql.org/docs/current/static/sql-copy.html
The simplest way to do this with Django (move one Django database to another, defined with a different model django database) is to write a 2 Django views and one jquery html page.
The first view will be in the original Django app. It will essentially create a json object model of the database and push it out on a get request. This is custom to your Django's models.
The second view will be in the new Django app. This will take in json data and format it to match your current Django database (fields might not match up exactly, hence the reason for doing this migration). You then just add elements into the new database just as you were creating a new Django model entry(example).
I personally use a one off jquery html page that gets the json data from the first view and posts it to the second one. You could exclude this piece and just write it all in python in the second view, but I find doing it this way to be much cleaner.

quickest and cleanest method for inserting multiple rows django

I am in a situation where I would have to insert multiple records into a postgre db through an ajax call, based on a foreignkey.
Currently I am using db1.db2_set.create(...) for each record, looping over a list of dictionaries.
Is this the best way to do it? It seems like I'm hitting the database for every insert.
I'm pretty sure that django will query database when you call save() method. So if you do something like:
for i in objects:
db1.db2_set.create(i)
db1.save()
It may acess database only once. But still, this might be usefull:
http://djangosnippets.org/snippets/766/
It's a middleware that you can add to see how many querys your django application uses in the every page you are accessing.

Django Evolution: How do I add a new field at a specific position?

Is there a way to tell Django Evolution to add a new field to a database table at a specific position, similar to the AFTER statement of (My)SQL?
I have a table with some columns and I want to add new_column after column1. Using SQL directly I would do this:
ALTER TABLE `db_table` ADD `new_column` DATETIME NULL DEFAULT NULL AFTER `column1`
For Django Evolution this translates to:
MUTATIONS = [
AddField('DbTable', 'new_column', models.DateTimeField, null=True, ...)
]
However, this would add new_column to the end of the table, is there something I can pass in for the dots in the above statement giving more control over the order?
Django does not depend or care about the column position in the database. My guess is that Django Evolution works the same way.
So you shouldn't depend or care too much about database internals either, in the end that is why you are using the ORM, right?
If you really have to do it, I suggest subclassing django_evolution.mutations.AddField and overwriting the add_column method to integrate the AFTER statement in the list of SQL statements this method returns. There might be better places, this would be a hack.

Categories