【发布时间】:2020-02-28 23:43:48
【问题描述】:
我在创建 django 对象时遇到了问题。我有两个模型
class League(models.Model):
league_id = models.IntegerField(primary_key=True)
league_name = models.CharField(max_length=20)
league_logo = models.URLField(null = True)
league_flag = models.URLField(null = True)
standings = models.IntegerField(null=True)
is_current = models.IntegerField(null=True)
class Fixture(models.Model):
fixture = models.IntegerField (primary_key=True)
league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL)
event_date = models.DateTimeField(null=True)
event_timestamp = models.DateTimeField(null=True)
当我尝试从我的夹具模型创建对象时,此时我在排名表中没有任何数据。我收到一个错误,
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/data/data/com.termux/files/home/storage/predictions/forecast/odds.py", line 53, in <module>
fixt = Fixture.objects.create_or_update(fixture_id = fixture_id,league_id_id = league_id,event_date = event_date,)
AttributeError: 'Manager' object has no attribute 'create_or_update'
>>> import odds
/data/data/com.termux/files/home/storage/predictions/forecast
Traceback (most recent call last):
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit
self._commit()
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: insert or update on table "dataflow_fixture" violates foreign key constraint "dataflow_fixture_league_id_id_674984dc_fk_dataflow_"
DETAIL: Key (league_id_id)=(780) is not present in table "dataflow_league".
就像我理解这个错误的发生是因为当我创建一个夹具对象和创建到达 League_id 字段的过程及其对 League 表中的 League_id 字段的引用时,此时不包含任何数据。我在想,为了解决这个问题,我可以更改创建对象的顺序并首先创建联赛对象,然后再创建夹具对象。但是我的联盟模型也有外键字段,可以引用不存在的对象。 django有什么办法可以解决这种麻烦吗???
【问题讨论】:
标签: python django django-models django-queryset django-orm