Django db raw MySQL执行

时间:2017-03-21 17:05:53

标签: python django sqlite

我有一个模型和自定义管理器

模型

class VideoDescription(models.Model):
    title_eng = models.CharField(max_length=120, unique=True)
    title_ru = models.CharField(max_length=120, unique=True)
    slug = models.SlugField(max_length=200, unique=True, blank=True)
    rating = models.IntegerField(default=0)
    pub_date_start = models.DateField()
    poster = models.ImageField(upload_to=get_poster_path)
    genre = models.CharField(validators=[validate_comma_separated_integer_list], max_length=10, default=0)
    description = models.TextField(blank=True)

objects = VideoDescriptionManager()

class VideoDescriptionManager(models.Manager):
def get_video_by_genre(self, genre):
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute('''select m.id, m.title_eng, m.title_ru, m.slug, m.rating, m.pub_date_start,
        m.poster, m.genre, m.description, COUNT(*) from main_app_videodescription m
                        where genre like "%%%s%%";''', [genre])
        result_list = []
        for row in cursor.fetchall():
            p = self.model(id=row[0], title_eng=row[1], title_ru=row[2], slug=row[3], rating=row[4],
                           pub_date_start=row[5], poster=row[6], genre=row[7], description=row[8])
            p.num_responses = row[9]
            result_list.append(p)
        return result_list

我有一个错误:

django.db.utils.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.

谷歌说我在原始SQL查询中将[流派]改为(流派),但它没有帮助。 我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:1)

sqlite不使用%s作为参数,它使用?

但无论是使用sqlite还是其他数据库,都无法使用参数替换在字符串中间插入参数。您需要单独构建字符串,然后使用参数插入它。所以:

param = "%{}%".format(genre)
cursor.execute('''select m.id, m.title_eng, m.title_ru, m.slug, m.rating, m.pub_date_start,
                  m.poster, m.genre, m.description, COUNT(*) from main_app_videodescription m
                        where genre like ?;''', [param])

请注意,使用.format无需双重转义百分比。