0

我有一个管理命令

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])

我可以通过输入命令名称并指定参数(id)来运行它

当我运行command 200-205时,for循环返回一个列表:

ids =[200, 201, 202, 203, 204, 205]

并将其放入查询中:

SELECT content FROM log WHERE id IN (200, 201, 202, 203, 204, 205)

辉煌!

当我运行command 200ids 将是:

ids = [200]

执行查询返回错误:

(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")

似乎SELECT content FROM log WHERE id IN (200)它应该不工作。

我在这里做错了什么?

4

2 回答 2

1

你的代码对我来说看起来不错,但我不熟悉那些 Django 库。几个(可能很明显)解决方法的想法:(1)构造两个不同的 SQL 语句来执行;在单 ID 的情况下,对于单 ID 的情况,SELECT content FROM log WHERE id =再次简单 (2),使用所需 ID 的两个实例创建一个数组,以便 Django 构造此 SQL: SELECT content FROM log WHERE id IN (200, 200)。换句话说,

else:
    ids.append(id)
    ids.append(id)
于 2012-05-31T17:17:44.083 回答
0

你没有遗漏一些括号吗?

SELECT content FROM log WHERE id IN 200

对比

SELECT content FROM log WHERE id IN (200)
于 2012-05-31T15:21:11.043 回答