0
votes

Django Version - 3.0

BaseModel - base_models/models.py

# Create your models here.

from django.db import models


class BaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)

base_models/__init__.py

from base_models.models import BaseModel

settings.py

INSTALLED_APPS = [
     ...,
     'base_models.apps.BaseModelsConfig',
     ...
]

Error -

File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/rm-api/base_models/__init__.py", line 1, in from base_models.models import BaseModel File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/rm-api/base_models/models.py", line 6, in class BaseModel(models.Model): File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/env/lib/python3.7/site-packages/django/db/models/base.py", line 107, in new app_config = apps.get_containing_app_config(module) File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/env/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/env/lib/python3.7/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

1
That is correct, you should import it in the ready method of the app configuration. Why exactly do you want to import this in the __init__.py?Willem Van Onsem
Hey @WillemVanOnsem , thanks, yes it's working fine but I was thinking of using something like from base_models import BaseClass? is there a way to achieve it?Vaibhav Sharma

1 Answers

0
votes

I found the answer, you cannot do that in Django 3.0. It seems like in this version on every app initialization self.check_apps_ready() function runs from apps/registry.py that itself checks from the INSTALLED_APPS from app/settings.py.

So here's how I used my BaseModel.

  1. python manage.py startapp base.
  2. deleted models.py file from base app
  3. created models directory in the same app.
  4. created the __init__.py file in base/models/.
  5. Initialised my models in base.py.
  6. Included the BaseModel in init.py(base/models/__init__.py) by from .base import BaseModel
  7. Finally in base/__init__.py include from .models import BaseModel
  8. Include BaseModel anywhere in the app by from base import BaseModel.

done!

Reference - https://docs.djangoproject.com/en/3.0/topics/db/models/#organizing-models-in-a-package