django查询中带有base10的int()的无效文字

时间:2022-12-27 22:32:49

I am trying to import an excel file into my database. The file contains an id column which is later saved to Foreignkey filed in django model.

我正在尝试将excel文件导入我的数据库。该文件包含一个id列,稍后将其保存到django模型中的Foreignkey。

st_id = row[10]
st_data = Student.objects.get(id=st_id)

Now when i save this data with .save() method, it saves the data but returns an unbound error 'st_data' referenced before assignment. The traceback is invalid literal for int() with base 10.

现在,当我使用.save()方法保存此数据时,它会保存数据,但会返回在分配之前引用的未绑定错误“st_data”。对于带有基数为10的int(),回溯是无效的文字。

Whats actually happening? It saves the correct data all right, but throws the invalid literal for int().

什么事实发生?它可以保存正确的数据,但会为int()抛出无效的文字。

EDIT: The overall concept is as follows:

编辑:整体概念如下:

try:
    st_id = row[10]
    print type(st_id) #this line returns both type float and str
    st_data = Student.objects.get(id=st_id)
except Exception as e:
    print e #here it throws an exception `invalid literal for int()`

st_dict = {
   'student': st_data,
}

obj = Section(**st_dict)
obj.save() #the correct data is saved to the database.

1 个解决方案

#1


1  

Probably, your row doesn't contains int's.

可能,你的行不包含int。

To fix it, just try:

要修复它,只需尝试:

st_data = Student.objects.get(id=int(st_id))

#1


1  

Probably, your row doesn't contains int's.

可能,你的行不包含int。

To fix it, just try:

要修复它,只需尝试:

st_data = Student.objects.get(id=int(st_id))