تخطي للذهاب إلى المحتوى
القائمة
لقد تم الإبلاغ عن هذا السؤال
3 الردود
22525 أدوات العرض

I am trying to retrieve a list in my database. My statement is this:

    cr.execute("select es.* from student_resource es where es.date between '"+str(date_from)+"' and '"+str(date_to)+"'")

where date_from and date_to are of type fields.date but when when executed, that is i am trying to access my view, it says:

TypeError: cannot concatenate 'str' and 'int' objects

What did i miss with my statement?

الصورة الرمزية
إهمال
أفضل إجابة

Hello,

As your fields are fields.date then you do not need to convert into string. Please write your query as like below.

cr.execute("select es.* from student_resource es where es.date between '" + date_from + "' and '" + date_to + "' ")
or
cr.execute("select es.* from student_resource es where es.date between '%s' and '%s' " %(date_from, date_to) )
Update : or
query = "select es.* from student_resource es where es.date between '%s' and '%s' " %(date_from, date_to)
cr.execute(query)

When you retrieve any date/datetime value from data base into any python variable it is always in string s

o no need to convert into string. 

I hope it will resole your issue.

Thanks. 

الصورة الرمزية
إهمال
الكاتب

I've tried your suggestion sir but I get "ValueError: unsupported format character 'W' (0x57) at index 545" when i try "...between ? and ? ",(date_from, date_to) )" i get "IndexError: tuple index out of range"

Just try as I have updated my answer. I have test it at my side it is executed perfectly.

أفضل إجابة

I think you can use the to_date() in psql for that.

Try like this:

cr.execute("select es.* from student_resource es where es.date between to_date(date_from, 'YYYY/MM/DD') and to_date(date_to, 'YYYY/MM/DD')")  
OR
cr.execute("select es.* from student_resource es where es.date between to_date("+str(date_from)+", 'YYYY/MM/DD') and to_date("+str(date_to)+", 'YYYY/MM/DD') ")

الصورة الرمزية
إهمال
أفضل إجابة

Quoting Psycopg official references (see here) :

Psycopg casts Python variables to SQL literals by type. Many standard Python types are already adapted to the correct SQL representation.

Don't manually add single quotes depending of the data type, let Psycopg do that for you.

cr.execute( 
"""INSERT INTO some_table (an_int, a_date, a_string) VALUES (%s, %s, %s);""", (11, datetime.date(2007, 07, 27), "Odoo rocks!"))

الصورة الرمزية
إهمال
المنشورات ذات الصلة الردود أدوات العرض النشاط
2
ديسمبر 19
4182
1
مارس 15
6190
0
فبراير 16
2845
2
أغسطس 15
6614
1
أغسطس 15
4531