Django raw Query aggreation function - django

I need to write django raw query function to get the sum value and then write to the csn file.
I write my query
for time in Tracking_details.objects.raw('SELECT *,sum=SUM(work_time) FROM structure_tracking_details WHERE employee_id='+ employee_id + ' GROUP BY project_structure ') :
writer.writerow([ time.project_structure,time.sum ])
it tells
no such column: sum
How do I write the query correctly?

Replace sum=SUM(work_time) with SUM(work_time) AS sum.
BTW, employee_id='+ employee_id + ' is a very poor way of building queries. And you should not do it. It makes your query prone to SQL Injection as Django doesn't check whatever query you pass in raw() function. You can pass parameters to the raw query like this -
Tracking_details.objects.raw('SELECT *, SUM(work_time) AS sum FROM structure_tracking_details WHERE employee_id = %s GROUP BY project_structure', [employee_id])
More details.

Related

Django How to select differrnt table based on input?

I have searched for the solution to this problem for a long time, but I haven't got the appropriate method.
Basically All I have is tons of tables, and I want to query value from different tables using raw SQL.
In Django, we need a class representing a table to perform the query, for example:
Routes.objects.raw("SELECT * FROM routes")
In this way, I can only query a table, but what if I want to query different tables based on the user's input?
I'm new to Django, back in ASP.NET we can simply do the following query:
string query = "SELECT * FROM " + county + " ;";
var bus = _context.Database.SqlQuery<keelung>(query).ToList();
Is this case, I can do the query directly on the database instead of the model class, and I can select the table based on the user's selection.
Is there any method to achieve this with Django?
You can run raw queries in Django like this -
From django.db import connection
cursor = connection.cursor()
table = my_table;
cursor.execute("Select * from " + table)
data = cursor.fetchall()

How do you insert variables into a database table using PostgreSQL via C++?

I have a C++ program that inserts values into a database table. I can't directly hardcode the values in because the data is constantly being updated, but I'm really confused about the syntax.
When I try to do this:
l.exec("INSERT INTO course VALUES(cid, term, 'subj',crse, sec, 'units', 'instructors');");
l.exec("INSERT INTO meeting VALUES(cid, term, 'type', 'days', 'time', 'build', room);");
l.exec("INSERT INTO enrolledin VALUES(cid, term, sid, 'major', 'classlevel', 'level', 'status', seat, numunits, 'grade');");
l.exec("INSERT INTO student VALUES(sid, 'surname', 'prefname', 'email');");
I get this error:
terminate called after throwing an instance of 'pqxx::undefined_column'
what(): ERROR: column "cid" does not exist
LINE 1: INSERT INTO course VALUES(cid, term, 'subj',crse, se...
^
HINT: There is a column named "cid" in table "course", but it cannot be referenced from this part of the query.
--
I was told that it's because I was inserting the literal string name instead of the values inside the string, and I'm confused as to how to insert the values inside the string via C++ while still using variable names.
Syntax of the used SQL INSERT query is incorrect. It should be:
INSERT INTO course (cid, subj) VALUES(1, 'subj');
You should specify table name together with columns to insert into and values after that. I reduced number of columns for simplicity. For a complete syntax of INSERT query check the PostgreSQL documentation.
To insert values from your variables you can do the following:
int cidValue = 1;
std::string subjValue = "subj";
l.exec("INSERT INTO course (cid, subj) VALUES(" + std::to_string(cidValue) + ", '" + l.esc(subjValue) + "')");
esc() function helps to prevent SQL injection attack.

How to prepare a C++ string for sql query

I have to prepare strings to be suitable for queries because these strings will be used in the queries as field values. if they contain a ' etc the sql query fails to execute.
I therefore want to replace ' with '' I have seen the code to find and replace a substring with a substring. but I guess the problem is a little tricky because replacing string also contains two single quotes '' replacing one quote ' so when I have to find the next occurance it would encounter a ' which was intentionally replaced.
I am using Sql lite C api and the example query might look like this
select * from persons where name = 'John' D'oe'
Since John Doe contain a ' the query will fail , so I want all occurances of ' in the name to replaced with ''
Any ideas how you guys prepares your field values in query to be used in sql ??? may be it's a basic thing but I am not too smart in C/C++.
your help would be very helpful
Use queries with arguments instead of replacing stuff, which could lead to several problems (like SQL injection vulnerabilities).
MySQL example:
sql::Connection *con = ...;
string query = "SELECT * FROM TABLE WHERE ID = ?";
sql::PreparedStatement *prep_stmt = con->prepareStatement(query);
prep_stmt->setInt(1, 1); // Replace first argument with 1
prep_stmt->execute();
This will execute SELECT * FROM TABLE WHERE ID = 1.
EDIT: more info for SQLite prepared statements here and here.
It depends on the SQL Library you are using. Some of them will have the concept of a PreparedStatement, which you will use question marks in place of the variables, then when you set those variables on the statement, it will internally ensure that you cannot inject sql commands.

Escaping queries in Django

I have the following method:
def select_query(self):
sql = "SELECT * FROM {t} WHERE 1".format(t=self._meta.db_table)
for column_name in self.distinguishing_column_names():
sql = sql + " AND {c} = {v}".format(c=column_name, v=getattr(self, column_name))
return sql
This will give me a query like this:
SELECT * FROM customer WHERE 1 AND name = JOHN SMITH AND customer_number = 11423 AND social_security_number = 1234567890 AND phone = 2323523353
Obviously, that's not going to work. Is there a way to get Django to quote this for me?
Note: I'm not asking for a prepared statement. That's something different.
Do you need to return a query this way? The proper way would be to call cursor with the query and the params as argument:
Does Python support MySQL prepared statements?
The correct way to format a query seems to be:
query = query % db.literal(args)
Where db is a mysql.Connection (or presumably any connection)
Apparently the answer is "no."

postgresql full text search query to django ORM

I was following the documentation on FullTextSearch in postgresql. I've created a tsvector column and added the information i needed, and finally i've created an index.
Now, to do the search i have to execute a query like this
SELECT *, ts_rank_cd(textsearchable_index_col, query) AS rank
FROM client, plainto_tsquery('famille age') query
WHERE textsearchable_index_col ## query
ORDER BY rank DESC LIMIT 10;
I want to be able to execute this with Django's ORM so i could get the objects. (A little question here: do i need to add the tsvector column to my model?)
My guess is that i should use extra() to change the "where" and "tables" in the queryset
Maybe if i change the query to this, it would be easier:
SELECT * FROM client
WHERE plainto_tsquery('famille age') ## textsearchable_index_col
ORDER BY ts_rank_cd(textsearchable_index_col, plainto_tsquery(text_search)) DESC LIMIT 10
so id' have to do something like:
Client.objects.???.extra(where=[???])
Thxs for your help :)
Another thing, i'm using Django 1.1
Caveat: I'm writing this on a wobbly train, with a headcold, but this should do the trick:
where_statement = """plainto_tsquery('%s') ## textsearchable_index_col
ORDER BY ts_rank_cd(textsearchable_index_col,
plainto_tsquery(%s))
DESC LIMIT 10"""
qs = Client.objects.extra(where=[where_statement],
params=['famille age', 'famille age'])
If you were on Django 1.2 you could just call:
Client.objects.raw("""
SELECT *, ts_rank_cd(textsearchable_index_col, query) AS rank
FROM client, plainto_tsquery('famille age') query
WHERE textsearchable_index_col ## query
ORDER BY rank DESC LIMIT 10;""")