首页 > 解决方案 > Django:使用夹具和 uuid 的 OnetoOne 关系

问题描述

我有一个名为 user 的模型,另一个名为 patient 的模型如下:

class Patient(Model):
    user = OneToOneField('users.User', on_delete=CASCADE, related_name="patient",
                          blank=True, null=True)

class User(Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

所有迁移都正常工作,现在我正在尝试使用固定装置将一些数据添加到数据库中。用户装置工作良好,但患者装置似乎没有检测到用户的 UUID:

django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "patients_patient" violates foreign key constraint "patients_patient_user_id_b53513b7_fk_users_user_id"
 DETAIL:  Key (user_id)=(97179680-7042-11ea-bc55-0242ac130003) is not present in table "users_user".

这是我的夹具的外观:

病人固定装置

[{
    "model": "patients.patient",
    "id": 1,
    "fields": {
      "user": "97179680-7042-11ea-bc55-0242ac130003"
    }
  },
]

用户夹具

[
    {
      "model": "users.User",
      "id": "97179680-7042-11ea-bc55-0242ac130003",
      }
    },
]

我该如何解决?

标签: djangouuiddjango-fixtures

解决方案


好的,找到解决方案!而不是id只使用pk


推荐阅读