Django TypeError: аргумент int () должен быть строкой, байтовым объектом или числом, а не списком

1

Новичок здесь. Я пишу сценарий загрузчика для веб-сайта, который использует CSV, загруженный с wrapsnet.org. Когда я пытаюсь запустить загрузчик, я получаю сообщение «TypeError: аргумент int () должен быть строкой, байтовым объектом или числом, а не списком».

Полная трассировка:

  File "loader.py", line 30, in <module>
    ref.save()
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 836, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 922, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 961, in _do_insert
using=using, raw=raw)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/query.py", line 1060, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1098, in execute_sql
for sql, params in self.as_sql():
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1051, in as_sql
for obj in self.query.objs
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1051, in <listcomp>
for obj in self.query.objs
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1050, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 990, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 766, in get_db_prep_save
prepared=False)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 758, in get_db_prep_value
value = self.get_prep_value(value)
  File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1849, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Loader.py:

import os, sys, string, csv, datetime, time, django, pytz

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "refugees.settings")

django.setup()

from reports.models import Country, State, City, RefugeeReport

from django.template.defaultfilters import slugify, urlize
from django.core.exceptions import ObjectDoesNotExist

reader = csv.reader(open("refugees0216.csv"), dialect=csv.excel)
next(reader)
for row in reader:

    refstate = row[0]
    refstate_slug = slugify(refstate)
    refstateid, refstateadded = State.objects.get_or_create(name=refstate, name_slug=refstate_slug)

    reforigin = row[3]
    reforigin_slug = slugify(reforigin)
    reforiginid, reforiginadded = Country.objects.get_or_create(name=reforigin, name_slug=reforigin_slug)

    popcity = row[6]
    popcity_slug = slugify (popcity)
    popcityid, popcityadded = City.objects.get_or_create(name=popcity, name_slug=popcity_slug)

    ref = RefugeeReport(country=reforiginid, state=refstateid, city=popcityid, year=row[1], city_total=row[6], state_total=row[2], country_total=row[4], all_countries=[7])
    print(ref)
    ref.save()

Models.py:

from django.db import models

class Country(models.Model):
    name=models.CharField(max_length=255)
    name_slug=models.SlugField()
    def __str__(self):
        return self.name

class State(models.Model):
    name=models.CharField(max_length=255)
    name_slug=models.SlugField()
    def __str__(self):
    return self.name
    def get_absolute_url(self):
        return "/reports/%s" % self.name_slug

class City(models.Model):
    state=models.ForeignKey(State)
    name=models.CharField(max_length=255)
    name_slug=models.SlugField()
    def __str__(self):
        return self.name
    def get_absolute_url(self):
        return "/reports/%s/%s" % (self.state.name_slug, self.name_slug)

class RefugeeReport(models.Model):
    country=models.ForeignKey(Country)
    state=models.ForeignKey(State)
    city=models.ForeignKey(City)
    year=models.CharField(max_length=255)
    city_total=models.IntegerField(default=0)
    state_total=models.IntegerField(default=0)
    country_total=models.IntegerField(default=0)
    all_countries=models.IntegerField(default=0)
    def __str__(self):
        return "%s, %s from %s" % (self.city.name_slug, self.state.name_slug, self.year)
    def get_absolute_url(self):
        return "/reports/%s/%s/%s" % (self.city.name_slug, self.state.name_slug, self.year)

Буду признателен за любые предложения, которые позволят вам заставить его работать.

Обновление: трассировка для печати всех переменных

  File "loader.py", line 29, in <module>
    print(ref, country, state, city, year, city_total, state_total, country_total, all_countries)
NameError: name 'country' is not defined
0
0

Я думаю, у вас есть ошибка в этой строке:

  ref = RefugeeReport(country=reforiginid, state=refstateid, city=popcityid, year=row[1], city_total=row[6], state_total=row[2], country_total=row[4], all_countries=[7])

Взгляните на all_countriesсвойство, я думаю, что это неверно:

all_countries=[7]

Измените его на:

 all_countries=row[7]
1
  • Хороший улов! Спасибо.
    elc3317
    12 июн.