I have an management command
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = "[id]"
def handle(self, id, **options):
ids = []
if '-' in id:
splitted = id.split('-')
for n in range(int(splitted[0]), int(splitted[1])+1):
ids.append(n)
else:
ids.append(id)
c = connection.cursor()
c.execute('SELECT content FROM log WHERE id IN %s', [ids])
I can run this by entering command name and specify paramater (id)
When I run command 200-205, the for loop returns a list:
ids =[200, 201, 202, 203, 204, 205]
And puts this in the query:
SELECT content FROM log WHERE id IN (200, 201, 202, 203, 204, 205)
Briljant!
When I run command 200 ids will be:
ids = [200]
Executing the query returns an error:
(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 '))' at line 1")
Seems like SELECT content FROM log WHERE id IN (200) is not working while it should.
What am I doing wrong here?
Your code looks OK to me, but I’m not fluent in those Django libraries. A couple of (perhaps obvious) workaround ideas: (1) construct two different SQL statements to be executed; in the one-ID case, it’s a simple
SELECT content FROM log WHERE id =(2) again for the one-ID case, make an array with two instances of the desired ID, so that Django constructs this SQL:SELECT content FROM log WHERE id IN (200, 200). In other words,