0
0

More than 1 year has passed since last update.

【ERROR!!!】ValueError: badly formed hexadecimal UUID string

Posted at

目的

DjangoRestframeworkを使って、APIの実装を行うこと。
そのためにモデルのマイグレーションを行いたいが、ValueError: badly formed hexadecimal UUID stringのエラーによって困っている。

結論

既にidがuuidでないレコードが存在する場合はそのレコードを削除すると無事にマイグレーションが行える。

実施環境

ハードウェア環境

項目 情報
OS macOS Catalina(10.15.7)
ハードウェア MacBook Air (11-inch, Early 2015)
プロセッサ 1.6 GHz デュアルコアIntel Core i5
メモリ 4 GB 1600 MHz DDR3
グラフィックス intel HD Graphics 6000 1536 MB

ソフトウェア環境

項目 情報
homebrew 3.3.8
mysql Ver 8.0.27 for macos10.15 on x86_64
python 3.8.12
django 3.1.2
anaconda 4.10.1
pip 21.2.4

経緯

djangoのmodels.pyのidフィールドを元々ただの自動採番の数字(1,2,3...)にしていたが、idは外部から読まれないようにuuidかつ編集不可に設定しようと思い、下記のように設定した。

id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)

しかしValueError: badly formed hexadecimal UUID string(16進数UUID文字列の形成がうまくできない)このエラーが表示されてしまったという経緯だ。

原因究明

少し調べると役に立ちそうな情報を見つけた。

The problem is that I had an existing record in the DB with a default integer autoincrement id, before I had specific that the id field on my model was a UUIDField. The value of this field was just 1, which was not a valid UUID hex string.
Removing this record fixed my issue.

おそらく自分も同じようにidをuuidにする前に、自動採番のidのレコードをいくつも追加していたため、これが原因であるとわかった。
models.pyでdefault=uuid.uuid4と設定しているにも関わらず、既存のコードはuuidではなかったため、このようなエラーが出ているようだ。

解決

上記のコメントと同様に、mysqlにログインし、既存のレコードを削除していく。

mysql> delete from users where id=1;

もう一度マイグレーションを実行してみる。

$ python manage.py makemigration
$ python manage.py migrate

無事マイグレーション完了!!解決!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0