开发者

Django Raw SQL give me TypeError not enough arguments

开发者 https://www.devze.com 2023-03-23 20:04 出处:网络
I\'ve got this raw query :开发者_开发知识库 counters = Counter.objects.raw(\"\"\" SELECT id, name FROM building_counter c

I've got this raw query :

开发者_开发知识库
counters = Counter.objects.raw("""
            SELECT id, name FROM building_counter c
            INNER JOIN scope_scope_buildings ssb 
                    ON c.building_id = ssb.building_id
                    AND ssb.scope_id = %s
            WHERE  energy_id = %s
            AND parent_id is not NULL
            AND type = "C"
           """, [self.id, energy_id])

The result gave me :

TypeError: not enough arguments for format string 
[2, 1L]

I don't understand what's wrong with it :s


The real problem is that you're passing in a list to params, but then you're trying to call repr on the result (I only know this because I got the same problem when running it in ipython). What you need to do is pass in a tuple:

counters = Counter.objects.raw("""
        SELECT id, name FROM building_counter c
        INNER JOIN scope_scope_buildings ssb 
                ON c.building_id = ssb.building_id
                AND ssb.scope_id = %s
        WHERE  energy_id = %s
        AND parent_id is not NULL
        AND type = 'C'
       """, (self.id, energy_id))

Or you can apply this patch to your django source and it'll turn these into tuples when you're in the shell.

If you don't use the shell for raw queries often, you can just ignore this though, since the rest of django handles list params just fine.


You must use '%s' instead of %s

counters = Counter.objects.raw("""
        SELECT id, name FROM building_counter c
        INNER JOIN scope_scope_buildings ssb 
                ON c.building_id = ssb.building_id
                AND ssb.scope_id = '%s'
        WHERE  energy_id = '%s'
        AND parent_id is not NULL
        AND type = 'C'
       """, [self.id, energy_id])


You also need to use %d for your first placeholder, since self.id will be an Integer and not a String. %d tells the string to expect an int in that slot.

0

精彩评论

暂无评论...
验证码 换一张
取 消