错误的值 - 在Django中建模的python

问题描述:

我遇到的问题是当试图在由Django模型创建的数据库中插入一些值时,这些值是严格数字的,但是当试图插入它时,我得到一个错误:错误的值 - 在Django中建模的python

567523 
<type 'int'> 
Warning: Incorrect integer value: 'id' for column 'id_unidad' at row 1 
cursor.execute(sql, ('id',)) 

我使用的MySQL的请求插入代码是:我使用

import MySQLdb 
import _mysql 

id = 567523 
print id 
print type(id) 

sql = """INSERT INTO gprs_evento (id_unidad) VALUES (%s)""" 

db = MySQLdb.Connect(host="localhost", user="*****",passwd="******",db="gp") 
cursor = db.cursor() 

try : 
    cursor.execute(sql, ('id',)) 
    db.commit() 
except _mysql.Error, e: 
    print "Error %d: %s" % (e.args[0], e.args[1]) 

的Django模型是:

from django.db import models 

class Evento(models.Model): 
    id_unidad = models.IntegerField(max_length=15) 

尝试在每个字段中插入数据库:

id: 13831010240120 
<type 'long'> 
ip: 3235021102 
<type 'long'> 
e: 2 
<type 'int'> 
H: 102718.0 
<type 'float'> 
LN: 210.128871 
<type 'float'> 
LO: 3203.323664 
<type 'float'> 
V: 28.0 
<type 'float'> 
A: 90.0 
<type 'float'> 
F: 40101.0 
<type 'float'> 

在模型中我使用了Field types的参考和尝试,并IntegerField,BigIntegerField,DecimalField但没有,我刚插入的15数量正常来自Python的字符。

您正试图插入字符串"id",而不是变量id的值。

它应该是:

cursor.execute(sql, (id,)) 

当然,没有理由要使用原始SQL这在所有。

+0

谢谢,就是因为这个原因,我是一个相对的新手编程python。问候和感谢。 – user987055 2012-03-10 17:37:31

正如丹尼尔所说,“没有理由使用原始SQL。”相反,你应该使用Django的模型语法插入新项目到DATEBASE,像这样:

e = Evento.objects.create(id_unidad=id) 

这一条线可以替代以下print type(id)一切。更重要的是,使用Django模型进行数据库操作可以免费获得SQL注入保护。