Python/Django - 需要一个字符串或类似字节的对象

我环顾四周,看到了一些我认为适用于我自己的代码但似乎什么也没做的解决方案。

我正在尝试从 JSON 文件中提取数据并将信息添加到数组中。然后,这些数组将用于将数据输入到我添加到数据库中的几个对象中(我知道,这是非常低效的,但是按照我编写原始脚本的方式,我不必将对象添加到数据库中。我是计划改变它)。

对象包含与其关联的日期时间。我使用 Python 的 strptime 函数将字符串转换为日期时间对象。

在我的 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)})

这是我的模型.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'),
]

类似问题的其他解决方案都说问题出在我的默认值上。然而,当我没有设置默认值时(如代码所示),我仍然会遇到同样的错误。

最佳答案

以防万一有人遇到这个最近的错误。

第 1 步:转到迁移文件夹“migrations”。

第 2 步:导航到迁移文件,最近的一个,例如“0008_auto_20210821_0912.py”。

第 3 步:将 DateField 的默认值从任何值更改为“2021-01-05”或 DateTimeField 的“2021-01-05 06:00:00.000000-09:00”

https://stackoverflow.com/questions/40234503/

相关文章:

php - 基于其他数组排序数组

r - 在 r 中为多个箱形图创建循环

json - R + fromJSON - 如何发送标题信息?

haskell - Haskell 中的 'let' 和变量

xcode - 我找不到 podfile

php - OMDb API 多个结果

php - 将变量从按钮传递到 Controller Laravel

vb.net - 为什么异步函数返回 System.Threading.Tasks.Task`1[S

c# - 如何从 MVC razor c# 中的动态模型获取属性值

spring - 基于模型变量+Spring表单+JSP的选中单选按钮