我正在建立一个新的django(2.2版)项目,并希望使用自定义用户模型。当我加载灯具数据时,失败并显示如下错误:
django.db.utils.IntegrityError:安装固定装置时出现问题:在表“ doctors_doctor”上插入或更新违反了外键约束“ doctors_doctor_user_ptr_id_ba968804_fk_doctors_user_id” 详细信息:表(doctors_user)中不存在键(user_ptr_id)=(1)。
从Django文档-https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project中,我意识到我在进行settings.py中的AUTH_USER_MODEL更改之前做了“ python manage.py migration”。因此,我尝试删除所有表并重做“ python manage.py migration”,但仍然遇到了这个问题。
以下是我的代码
settings.py
AUTH_USER_MODEL='doctors.User'
models.py
class User(AbstractUser):
mobile = models.CharField(max_length=30)
fixtures_autodump = ['dev_users']
class Meta:
db_table = 'doctors_user'
def __str__(self):
return self.username
class Doctor(User):
personal_id = models.CharField(max_length=255, blank=True)
fixtures_autodump = ['dev_users']
class Meta:
db_table = 'doctors_doctor'
def __str__(self):
return self.username
dev_users.json
[
{
"model": "doctors.doctor",
"pk": 1,
"fields": {
"date_joined": "2019-06-16T09:09:56.127Z",
"email": "user1@localhost.dev",
"first_name": "user1",
"groups": [],
"is_active": true,
"is_staff": true,
"is_superuser": true,
"last_login": null,
"last_name": "test",
"password": "pbkdf2_sha256$36000$nITgYnD9lKzm$cXGlthNYJDrrihQikgyh7HO5hm2fNvH71+fiCoMyIpY=",
"user_permissions": []
}
},
{
"model": "doctors.doctor",
"pk": 2,
"fields": {
"date_joined": "2019-06-16T09:09:56.127Z",
"email": "user2@localhost.dev",
"first_name": "user2",
"groups": [],
"is_active": true,
"is_staff": false,
"is_superuser": false,
"last_login": null,
"last_name": "test",
"password": "pbkdf2_sha256$36000$ohIbxnbyKjNm$smg+FvfhT1cF1kLt93EDz/n5KyfkDupIgkihsNIHQS8=",
"user_permissions": []
}
}
]
我希望加载夹具数据可以成功,请帮忙。
答案 0 :(得分:0)
我在JSON文件中需要2条记录,一个是User,另一个是我的自定义用户。这两个的pk值应该相同。这就是Django loaddata为自定义用户工作的方式。我进行了更改,并且有效。