LoginSignup
1
0

【Django】「...doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS」エラーについて

Posted at

エラー内容

DjangoでDBからデータ取得するモジュールを実行させたら、以下のエラーになりました。

RuntimeError: Model class sample.models.Sample doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

原因と解決策

SampleモデルがDjangoアプリケーションに正しく登録されていないか、app_labelが指定されていない、と言われています。アプリケーションの登録はsettings.pyINSTALLED_APPSで行いますが、ここには記載済みでした。

app_labelというのをモデルに明示的に記載することで解決した、という記事もあったので、参考にしてみたら解決しました。

通常、Djangoはモデルの所属アプリケーションを自動的に判断してくれますが、一部の状況では自動判断できない場合があります。例えば、今回私はアプリケーションディレクトリの外で、データ取得のコマンドを叩くモジュールを試験的に置いていました。そのため、Djangoがどのアプリケーションに属するかを正確に判断できなかったのでしょう。

ということで、以下のようにapp_labelを追記。

models.py
from django.db import models

class Sample(models.Model):

    class Meta:
        app_label = 'sample' # ここを追加
        db_table = 'sample'

app_labelの値は、INSTALLED_APPS内のDjangoアプリケーション名と一致する必要があります。

1
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
1
0