填充外键字段时,NOT NULL约束失败错误

时间:2018-01-06 05:14:56

标签: python django django-models sqlite

我正在尝试运行我编写的脚本,将一些数据从json文件移动到我的数据库中,并不断收到同样的错误。

回溯:

Traceback (most recent call last):
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: clan_participant.completed

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "participant_updater.py", line 32, in <module>
    message = participant_updater()
  File "/home/jamtime/clansite/database_updaters.py", line 548, in participant_updater
    update_db()
  File "/home/jamtime/clansite/database_updaters.py", line 512, in update_db
    character=char_obj
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 653, in create
    return super(RelatedManager, self.db_manager(db)).create(**kwargs)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert
    using=using, raw=raw)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1107, in execute_sql
    cursor.execute(sql, params)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: clan_participant.completed

数据库存在,我已经迁移了所有当前更改。我还在模型的外键字段中设置了null=Trueblank=True

(参与者模型是给出问题的模型)

models.py

class Clan(models.Model):
    # stuff...

class Player(models.Model):
    # stuff...

class ClanMember(models.Model):
    clan = models.ForeignKey(Clan, related_name='ClanMembers')
    player = models.OneToOneField(Player, on_delete=models.CASCADE, primary_key=True, related_name="ClanMember")
    # stuff...

class Character(models.Model):
    player = models.ForeignKey(Player, related_name='Characters')
    # stuff...

class Activity(models.Model):
    characters = models.ManyToManyField(Character, related_name='Activities')
    # stuff...

class Team(models.Model):
    activity = models.ForeignKey(Activity, related_name='Teams', db_index=True)
    # stuff...

class Participant(models.Model):
    related_team = models.ForeignKey(Team, related_name='Participants', db_index=True)
    character = models.ForeignKey(Character, on_delete=models.CASCADE, related_name='ParticipationInstances', null=True, blank=True)
    displayName = models.CharField(max_length=30, default='')

    def __str__(self):
        return str(self.related_team.__str__()+' - '+self.displayName)

发生错误的脚本部分:

                if not activity.private: # can insert mode separation here
                    try:
                        team = activity.Teams.get(teamId=p_fields["team"])

                    except ObjectDoesNotExist:
                        if int(p_fields["team"]) == -1:
                            team = activity.Teams.create(
                                # stuff...
                                )
                try:
                    if not team.Participants.filter(displayName=p_fields["displayName"]).exists():
                        if mods.Player.objects.filter(membership_id=p_fields["membershipId"]).exists():
                            p_obj = mods.Player.objects.get(membership_id=p_fields["membershipId"])
                        else:
                            p_obj = mods.Player(
                                # stuff...
                                )

                        if p_obj.Characters.filter(char_id=p_fields["characterId"]).exists():
                            char_obj = p_obj.Characters.get(char_id=p_fields["characterId"])

                        else:
                            char_obj = p_obj.Characters.create(
                                # stuff...
                                )

                        new_p = team.Participants.create(         # This part is giving the error
                            displayName=p_fields["displayName"],  # This part is giving the error
                            character=char_obj                    # This part is giving the error, this line specifically
                            )                                     # This part is giving the error

我也尝试过创建对象并在之后添加字符字段,但是在我尝试添加字符字段的行上会出现相同的错误。

长期坚持这一点,非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

事实证明,在参与者模型中有一个布尔字段,其默认值设置为无completed = models.BooleanField(default=None),这对于布尔字段是不可能的。