-1

this is my current query

cursor = connection.cursor()
cursor.execute('SELECT *'\
    'FROM students' \
    'WHERE numberofclasses > 4')
list = cursor.fetchall()

now I wish to add to the string:

  1. that registrationdate was in the past month --> how do I calculate and add the result to the string
  2. the name starts with 'l' --> how do i add name like '%l' into the above string

Note:

  1. it's important for my question to keep the string format of '...'\ '...'\ and not write it in between ''' ... '''
  2. this is an example for a much complicated query that must be executed this way and not through Django ORM platform.
liv a
  • 3,232
  • 6
  • 35
  • 76
  • I guess this is a simplified version of the query you'd like to execute, but if it is not: than just use the query managers as present within Django. This would safe you lots of trouble. https://docs.djangoproject.com/en/1.8/topics/db/queries/ – Wouter Klein Heerenbrink Jun 12 '15 at 10:59
  • @WouterKleinHeerenbrink edited my question, (note 2) the query i need to run is too complicated for django – liv a Jun 12 '15 at 11:09

1 Answers1

0

Lets break it up in few questions:

  1. How to determine 'past month' python date of the previous month
  2. Format for your database depends on the backend your using Mysql: https://dev.mysql.com/doc/refman/5.1/en/date-and-time-literals.html Postgres: http://www.postgresql.org/docs/9.1/static/datatype-datetime.html
  3. Entering the value in your string:

Your could concatenate a formatted date:

cursor.execute('SELECT *'\
    'FROM students' \
    'WHERE numberofclasses > 4' \
    'AND mydate > \'%s\'', [month_ago.isoformat()])

https://docs.python.org/2/library/datetime.html#datetime.date.isoformat

I do not understand your second question, for this seems to contain the answer already.

Community
  • 1
  • 1
  • the embedding of `month_ago.isoformat()` raises the error of: `operator does not exist: timestamp without time zone >= integer` I think I need to add the **'** before and after the date in c language it will be like this `\'` but in python it doesn't work – liv a Jun 12 '15 at 13:01
  • you're right, I forgot the quotes so Postgres will see this as an integer. The escaping in Python is equal to C, `\'`. If for some reason this does not work you could go for double quotes of course. I also changed the way to insert arguments following https://docs.djangoproject.com/en/1.8/topics/db/sql/#passing-parameters-into-raw – Wouter Klein Heerenbrink Jun 12 '15 at 13:58