0

Parent Model:

id = auto_generated
add_me = IntegerField()

Child Model:

id = ForeignKey(Parent)
my_date= DateTime(auto_now_add=True)

and,

today = django.util.timezone.now()
time = today - timedelta(days=10)

now I want to retrieve records as:

child.objects.filter(my_date__lte= time + 
(timedelta(days=1)*F('id__add_me')))

Everthing works fine except:

(timedelta(days=1)*F('id__add_me'))

I am using MYSQL: I get:

django.db.utils.ProgrammingError:
 (1064, "You have an error in your SQL syntax;
 check the manual that corresponds to your MySQL
 server version for the right syntax to use near
 '* `parent`.`add_me`))))' at line 1")

Query Generated is like:

SELECT*  FROM `child INNER JOIN `parent` ON
 (`child`.`id` = `parent`.`id`) WHERE
  ( `child`.`my_date` <= ((2018-07-30 09:11:18.670900 
  + (INTERVAL '86400.000000' SECOND_MICROSECOND * `parent`.`add_me`))))

As you can see * (multiplication) is with INTERVAL.
I hard coded query putting the parent.add_me inside the INTERVAL and got it right,
how can I do so via Django? i.e. DATE_ADD in django

I want to reduce days from a datetime field, where days are stored in master table field.
Maybe it doesn't work with MYSQL, so please provide an alternative solution to such.

UPDATED:

Somehow I found error by writing MYSQL query as:

SELECT * FROM child INNER JOIN parent ON" \
child.id = parent.id WHERE
child.my_date<= '" + str(time) + \
"' + INTERVAL parent.add_me DAY "

The problem was with single quotes (') i.e. in mysql for <= the datetime shall be within single quotes else won't work. i.e.
2018-07-30 09:11:18.670900 shall be written as
'2018-07-30 09:11:18.670900' if adding with INTERVAL,
But as queries are generated by Django, how do I achieve that?

Aashish Gahlawat
  • 409
  • 1
  • 7
  • 25

0 Answers0