我环顾四周,并且我已经看到了一些我认为可以用于我自己的代码的解决方案,但似乎什么也没做。
我正在尝试从JSON文件中提取数据并将信息添加到数组中。然后,数组将用于将数据输入到我添加到数据库的多个对象中(我知道,这非常低效,但是我编写原始脚本的方式,我没有必要将对象添加到数据库中。我打算改变它。)
对象包含与之关联的日期时间。我使用Python的strptime函数将字符串转换为datetime对象。
在我的models.py中,我有一个日期时间的DateTimeField。
但是,当我尝试迁移时,出现以下错误:
TypeError: expected string or bytes-like object
以下是整个追溯:
Applying interactive_table.0016_auto_20161024_2259...Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
field,
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 231, in add_field
self._remake_table(model, create_fields=[field])
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table
self.effective_default(field)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 221, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 755, in get_db_prep_save
prepared=False)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1438, in get_db_prep_value
value = self.get_prep_value(value)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1417, in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1275, in get_prep_value
return self.to_python(value)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1378, in to_python
parsed = parse_datetime(value)
File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/utils/dateparse.py", line 93, in parse_datetime
match = datetime_re.match(value)
供参考,这是我的views.py:
def getInfo(counter, hekJSON):
for counter in range(len(hekJSON["Events"])):
dateAndTimeHEK.append(convertTimes(hekJSON["Events"][counter]["startTime"]))
xcen.append(float("%.2f" % hekJSON["Events"][counter]["xCen"]))
ycen.append(float("%.2f" % hekJSON["Events"][counter]["yCen"]))
xfov.append(float("%.2f" % hekJSON["Events"][counter]["raster_fovx"]))
yfov.append(float("%.2f" % hekJSON["Events"][counter]["raster_fovy"]))
sciObj.append(hekJSON["Events"][counter]["sciObjectives"])
def convertTimes(dateAndTime):
dateTime = datetime.datetime.strptime(dateAndTime, '%Y-%m-%d %H:%M:%S')
return dateTime
def display(request):
noaaNmbr='11809'
#for right now, this is the only active region that I'm pulling data for. When I get the graph up and running, I will make it more interactive for the user so that he can
urlData = "http://www.lmsal.com/hek/hcr?cmd=search-events3&outputformat=json&instrument=IRIS&noaanum="+ noaaNmbr +"&hasData=true"
webUrl = urlopen(urlData)
counter = 0
data = webUrl.read().decode('utf-8')
hekJSON = json.loads(data)
getInfo(counter, hekJSON)
for i in range(getNumberOfEntries(hekJSON)):
observation = models.HEK_Observations(noaaNmbr=noaaNmbr, dateAndTime=dateAndTimeHEK[i], xcen=xcen[i], ycen=ycen[i], xfov=xfov[i], yfov=yfov[i], sciObj=sciObj[i])
observation.save()
return render(request, 'template.html', {'obj': models.HEK_Observations.objects.filter(noaaNmbr=noaaNmbr)})
这是我的models.py:
from django.db import models
import datetime
class HEK_Observations(models.Model):
dateAndTime = models.DateTimeField(max_length = 40, default = None, verbose_name = 'Date And Time')
这是我的urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# /table/
url(r'^$', views.display, name='display'),
]
类似问题的其他解决方案已经说过问题在于我的默认值。但是,当我没有设置默认值(如代码中所示)时,我仍然会得到相同的错误。
答案 0 :(得分:1)
您在迁移时遇到了错误,因此我猜测您的日期时间字段是一个字符串,并且您已将其设为日期时间字段。问题似乎是您的迁移从这些文本元素转变为日期。您可能需要清理数据库,转储数据库(如果是测试数据)或制作更好的手动迁移脚本。
让迁移变得不完美 - 如果您拥有不同格式的现有数据,则必须制作代码以将数据修改为新格式并保留信息。
如果它只是测试数据(通常是这样),你可以直接截断表 - 现在手动删除,(甚至删除数据库),或者在迁移脚本中使用一行。
其糟糕的形式是删除&#39;你的迁移文件并重新制作(特别是如果你有多个用户),但是如果你有很好的控制过程,可以做一些干净的版本(即每个版本一次迁移)。
答案 1 :(得分:0)
您应该删除迁移文件,然后再次运行迁移