Django: jsonファイルから初期データ投入しようとすると、存在しないデータのプライマリーキーの重複エラーが発生してしまいます。
以下に発生している問題の詳細等を記載しましたので、アドバイスいただけたらと思います。
前提
・フレームワークはDjango、DBはpostgreSQL、VMはDockerを使用。
・カスタムユーザーのモデルを作成して、マイグレーション済み。
・プロジェクト内に、account アプリのフォルダを作成。
・account アプリのディレクトリに、以下のmodels.pyを作成し、カスタムユーザーの作成・マイグレーションに使用。
account/models.py
from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): account_name = models.CharField(max_length=20) user_name = models.CharField(max_length=20) first_name = models.CharField(max_length=20,blank=True, null=True) family_name = models.CharField(max_length=20,blank=True, null=True) company_name = models.CharField(max_length=30,blank=True, null=True) email_address = models.EmailField() introduction = models.TextField() avatar = models.FileField(upload_to='account-avatar/') created_at = models.DateTimeField(auto_now_add=True) last_updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.account_name
実現したいこと
以下のjsonファイルを使用して、DBに初期データを投入したい。
[ { "model": "account.user", "pk": 1, "fields": { "account_name": "TANAKA", "user_name": "tanaka2564", "first_name": "Taro", "family_name": "Tanaka", "company_name": "", "email_address": "", "introduction": "helo world", "avatar": "account_avatar_1.png", "created_at": "2021-05-8T13:30:00.000Z", "last_updated_at": "2021-05-10T13:30:00.000Z" } }, { "model": "account.user", "pk": 2, "fields": { "account_name": "SUZUKI", "user_name": "syzuki2564", "first_name": "Jiro", "family_name": "Suzuki", "company_name": "", "email_address": "", "introduction": "helo world", "avatar": "account_avatar_1.png", "created_at": "2021-05-8T13:30:00.000Z", "last_updated_at": "2021-05-10T13:30:00.000Z" } }, { "model": "account.user", "pk": 3, "fields": { "account_name": "SATO", "user_name": "sato2564", "first_name": "Saburo", "family_name": "Sato", "company_name": "", "email_address": "", "introduction": "helo world", "avatar": "account_avatar_1.png", "created_at": "2021-05-8T13:30:00.000Z", "last_updated_at": "2021-05-10T13:30:00.000Z" } }, { "model": "account.user", "pk": 4, "fields": { "account_name": "UEKI", "user_name": "ueki2564", "first_name": "Shiro", "family_name": "Ueki", "company_name": "", "email_address": "", "introduction": "helo world", "avatar": "account_avatar_1.png", "created_at": "2021-05-8T13:30:00.000Z", "last_updated_at": "2021-05-10T13:30:00.000Z" } }, { "model": "account.user", "pk": 5, "fields": { "account_name": "KOBAYASHI", "user_name": "kobayashi2564", "first_name": "Goro", "family_name": "Kobayasi", "company_name": "", "email_address": "", "introduction": "helo world", "avatar": "account_avatar_1.png", "created_at": "2021-05-8T13:30:00.000Z", "last_updated_at": "2021-05-10T13:30:00.000Z" } } ]
発生している問題・エラーメッセージ
docker-compose run web ./manage.py loaddata user.json
を実行し、初期データを投入しようとすると、以下のエラーメッセージ が表示される。
account/migrations/0002_auto_20210510_0727.py - Alter field account_name on user - Alter field company_name on user - Alter field family_name on user - Alter field first_name on user - Alter field user_name on user hirotosatoh@mbp:~/project/thai_qiita (feature/create_test_data_for_account_application *)$ docker-compose run web ./manage.py migrate Creating thai_qiita_web_run ... done Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions Running migrations: Applying account.0002_auto_20210510_0727... OK hirotosatoh@mbp:~/project/thai_qiita (feature/create_test_data_for_account_application *)$ docker-compose run web ./manage.py loaddata user.json Creating thai_qiita_web_run ... done Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "account_user_username_key" DETAIL: Key (username)=() already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/code/./manage.py", line 22, in <module> main() File "/code/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label obj.save(using=self.using) File "/usr/local/lib/python3.9/site-packages/django/core/serializers/base.py", line 223, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 780, in save_base updated = self._save_table( File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 873, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 910, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1377, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: Problem installing fixture '/code/account/fixtures/user.json': Could not load account.User(pk=2): duplicate key value violates unique constraint "account_user_username_key" DETAIL: Key (username)=() already exists.
プライマリーキー2のデータが重複していることによるエラーと思われるが、account_userのテーブルに既存のデータが存在しないため、なぜ、このエラーが表示されるか、わからなかった。
試したこと①
account.User(pk=2): duplicate key ``` とエラーが表示されていたため、jsonファイルからid2のユーザーを削除し、再度データ投入を試みた。 すると今度は、 ```ここに言語を入力 account.User(pk=3): duplicate key
とエラーが表示された。
同様に、id2と3を削除し、再度データ投入を実行すると、
account.User(pk=4): duplicate key
とエラーが表示された。
上から数えて2番目のidになぜか重複エラーが発生する。
試したこと②
postgreSQLのDB内に入り、account_userのテーブルに既存のデータが存在するか確認したが、やはり、データ投入前なので、既存のデータはなかった。
試したこと③
以下のコマンドを実行し、マイグレーションや作成したDBを、一度削除し、作り直した。
docker-compose run web ./manage.py showmigrations docker-compose run web ./manage.py migrate --fake admin zero docker-compose run web ./manage.py migrate --fake auth zero docker volume ls docker-compose down docker volume rm ryuukakusan_db docker-compose up --build -d docker-compose run web ./manage.py showmigrations docker-compose run web ./manage.py makemigrations docker-compose run web ./manage.py migrate
しかし、結果は変わらず、初期データ投入を試みると、
account.User(pk=2): duplicate key ``` とエラーが表示されてしまう。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。