尝试从Django模型创建对象时遇到问题。我有固定模型
from django.db import models
from django.contrib.postgres.fields
import JSONField
import datetime
from django.utils import timezone
class Fixture(models.Model):
fixture = models.IntegerField(primary_key=True)
league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL, to_field="league")
event_date = models.DateTimeField(null=True)
event_timestamp = models.DateTimeField(null=True)
firstHalfStart = models.DateTimeField(null=True)
secondHalfStart = models.DateTimeField(null=True)
round_count = models.CharField(max_length=10)
status = models.CharField(max_length=20)
statusShort = models.CharField(max_length=15)
elapsed = models.IntegerField(null=True)
venue = models.CharField(max_length=170)
referee = models.CharField(max_length=70)
home_team_id = models.IntegerField(null=True)
away_team_id = models.IntegerField(null=True)
goal_of_home_team = models.IntegerField(null=True)
goal_of_away_team = models.IntegerField(null=True)
half_time_score = models.CharField(max_length=15)
full_time_score = models.CharField(max_length=15)
extratime = models.CharField(max_length=50)
penalty = models.CharField(max_length=50)
lastModified = models.DateTimeField(auto_now=True)
我有一个json文件,我在其中存储一些我要从中创建此模型对象的json数据
fixtures_date = open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagues_date.txt"), "r")
leagues_json = json.load(fixtures_date)
leagues_json = leagues_json["api"]["fixtures"]
for item in leagues_json:
fixture_id = item["fixture_id"]
league_id = item["league_id"]
event_date = item["event_date"]
event_timestamp = item["event_timestamp"]
firstHalfStart = item["firstHalfStart"]
secondHalfStart = item["secondHalfStart"]
round_count = item["round"] status = item["status"]
statusShort = item["statusShort"]
elapsed = item["elapsed"]
venue = item["venue"]
referee = item["referee"]
home_team_id = item["homeTeam"]["team_id"]
away_team_id = item["awayTeam"]["team_id"]
goal_of_home_team = item["goalsHomeTeam"]
goal_of_away_team = item["goalsAwayTeam"]
half_time_score = item["score"]["halftime"]
full_time_score = item["score"]["fulltime"]
extratime = item["score"]["extratime"]
penalty = item["score"]["penalty"]
现在我正试图从此变量创建对象
fixt = Fixture.objects.create(fixture = fixture_id,
league_id_id = league_id,
event_date = event_date,
event_timestamp = datetime.datetime.fromtimestamp(event_timestamp),
firstHalfStart = firstHalfStart,
secondHalfStart = secondHalfStart,
round_count = round_count,status =status,
statusShort = statusShort,
elapsed = elapsed,
venue = venue,referee= referee,
home_team_id = home_team_id,
away_team_id = away_team_id,
goal_of_home_team = goal_of_home_team,
goal_of_away_team = goal_of_away_team,
half_time_score = half_time_score,
full_time_score = full_time_score,
extratime = extratime,
penalty = penalty,
lastModified = timezone.now())
虽然我正在运行此脚本。我收到此错误,这里是完整的Traceback
>>> import fixture
/data/data/com.termux/files/home/storage/predictions/forecast
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/data/data/com.termux/files/home/storage/predictions/forecast/fixture.py", line 53, in <module>
fixt = Fixture.objects.create(fixture = fixture_id,league_id_id = league_id,event_date = event_date,event_timestamp = datetime.datetime.fromtimestamp(event_timestamp),firstHalfStart = firstHalfStart,secondHalfStart = secondHalfStart, round_count = round_count,status =status,statusShort = statusShort,elapsed = elapsed,venue = venue,referee= referee,home_team_id = home_team_id, away_team_id = away_team_id, goal_of_home_team = goal_of_home_team,goal_of_away_team = goal_of_away_team, half_time_score = half_time_score,full_time_score = full_time_score,extratime = extratime,penalty = penalty,lastModified = timezone.now())
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1334, in execute_sql
for sql, params in self.as_sql():
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1278, in as_sql
for obj in self.query.objs
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1278, in <listcomp>
for obj in self.query.objs
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1277, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1218, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 789, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1429, in get_db_prep_value
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1408, in get_prep_value
value = super().get_prep_value(value)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1268, in get_prep_value
return self.to_python(value)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1369, in to_python
parsed = parse_datetime(value)
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/utils/dateparse.py", line 106, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
从这次追溯中,我不明白我在做什么错。谁能指导我
UPD 我的Fixture模型具有四个潜在的datetime字段,并且每个字段的json值都具有以下数据类型
event_timestamp = <class 'int'>
event_date = <class 'str'>
但是 firstHalfStart 和 secondHalfStart 有时包含“整数”值,有时包含“ NoneType”值
答案 0 :(得分:0)
Django的Feature1
通常可用于Python DateTimeField
和datetime
对象,但是它可以自动将字符串解析为date
或datetime
对象。
您试图插入模型中date
字段中的json
数据的某个地方类型不正确。 Django会尝试自动为您解析它,但失败了。
在传递给datetime
datetime
方法之前,请确保所有datetime
字段都是有效的model
字符串或正确解析了时间戳