简体   繁体   中英

invalid literal for int() with base10 in django query

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.

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 .

Whats actually happening? It saves the correct data all right, but throws the invalid literal for 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.

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

To fix it, just try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM