2016-10-25 6 views
0

주위를 둘러 보았습니다. 내 코드에서 작동 할 것이라고 생각했지만 몇 가지 해결책을 찾지 못했습니다.Python/Django - 문자열 또는 바이트와 같은 객체가 필요합니다.

JSON 파일에서 데이터를 가져 와서 배열에 정보를 추가하려고합니다. 배열은 데이터베이스에 추가하는 여러 객체에 데이터를 입력하는 데 사용됩니다. (이것은 매우 비효율적이지만 원본 스크립트를 작성한 방식대로 데이터베이스에 객체를 추가 할 필요가 없습니다.) 변경 계획).

개체에 연결된 날짜 시간이 있습니다. 파이썬의 strptime 함수를 사용하여 문자열을 datetime 객체로 변환했습니다.

내 models.py에는 datetime에 대한 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)}) 

내 모델은 다음과 같습니다.

문제가 내 기본 값으로 거짓말을 유사한 문제에

from django.conf.urls import url 
from . import views 

urlpatterns = [ 
    # /table/ 
    url(r'^$', views.display, name='display'), 
] 

다른 솔루션은 말했다 : 63,210

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입니다. 그러나 코드에 표시된 것과 같은 기본값을 설정하지 않으면 여전히 동일한 오류가 발생합니다.

+0

첫째, 이전 중에이 문제가 발생했기 때문에 마이그레이션을 표시하지 않아도됩니까? 그리고 문제와 관련이 없지만 파이썬에서 루프를 수행하는 방법을 배워야합니다. 힌트 :'for x in range (len (whatever))'는 끔찍한 반 패턴이다. –

+0

@DanielRoseman 마이그레이션을 "표시"한다는 것은 migrations 폴더에 생성 된 실제 파일을 표시한다는 의미입니까? –

답변

1

마이그레이션에서 hte 오류가 발생하므로 날짜/시간 필드가 문자열이고 날짜 필드로 변경했다고 생각합니다. 문제는 텍스트 요소에서 날짜로 마이 그 레이션하는 방법 인 것 같습니다. 잠재적으로 데이터베이스를 덤프 (테스트 데이터 인 경우)하거나보다 나은 수동 마이그레이션 스크립트를 만들어야합니다.

마이그레이션 만들기가 완벽하지 않습니다. 기존 데이터가 다른 형식으로되어있는 경우 데이터를 새로운 형식으로 수정하고 정보를 보존해야하는 코드를 작성해야합니다.

평상시처럼 데이터를 테스트하는 경우 수동으로 지금 수동으로 (데이터베이스를 짝수로 삭제) 또는 마이그레이션 스크립트에서 한 줄만 사용하여 테이블을자를 수 있습니다.

마이 그 레이션 파일을 '삭제'하고 다시 작성하게하는 나쁜 형식이지만 (특히 사용자가 여러 명인 경우), 제어가 좋은 프로세스가있는 경우 클린 릴리스를 수행 할 수 있습니다 (즉, 해제).

관련 문제