6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Django】Modelに定義したForeignKeyで発生する循環Importを解決する

Posted at

概要

ハマったのでメモ。

構成

books/models.py

下記のように、ForeignKeyの引数にクラスを指定している場合です。

from accounts.models import User

class Book(models.Model):
    ....
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    ....

accounts/models.py

from books.models import Book

class User(AbstractUser):
    ....
    favorite_book = models.ForeignKey(Book, on_delete=models.PROTECT)
    ....

books/models.pyaccounts/models.pyの中身をimportしており、accounts/models.pyでもbooks/models.pyでimportしています。

エラー

循環importです。
importした先でimportが起き、またそこで逆のimportが起きてという感じです。
下記ようなエラーが発生します。

ImportError: cannot import name 'Book' from 'accounts.models' (/myproject/accounts/models.py)

解決方法

DjangoのForeignKeyで指定するモデルは、クラスを文字列指定で書くことができます。
そのため、下記のように指定すればimport宣言が必要とならず、循環Importが解決できます。

books/models.py

class Book(models.Model):
    ....
    user = models.ForeignKey('accounts.User', on_delete=models.PROTECT)
    ....

accounts/models.py

from books.models import Book

class User(AbstractUser):
    ....
    favorite_book = models.ForeignKey('books.Book', on_delete=models.PROTECT)
    ....

根本的な解決としてはクラス設計を再考する必要がありそうです...

最後に

DjangoのModelに定義したForeignKeyが原因となって発生する、循環Importを解決する方法をまとめました。
エラーで悩んでいる方は是非ご参考にしてください。

6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?