Lucas
Lucas

Reputation: 853

How to create a package of models in Django

Having a quite large models.py file (which contains several models), I'm trying to refactor, with one model per file.

I'm therefore trying to create a models package, with the following structure:

Unfortunately, I cannot get Django lazy reference mechanism to work well, i.e.:

first_model = models.ForeignKey('app.FirstModel')

returns the error that Django cannot find the model.

Any idea? Thanks!

Upvotes: 6

Views: 5269

Answers (3)

codeandfire
codeandfire

Reputation: 465

It should work, make sure that in __init__.py you are importing all the models from first_model.py and second_model.py.

from .first_model import FirstModel
from .second_model import SecondModel

EDIT: If you want to retrieve the models as app_label.model_name, then you will have to import them in __init__.py, otherwise you can try the following:

Use https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.apps.get_model

Or you can use ContentTypes: https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#methods-on-contenttype-instances

Upvotes: 6

Lemayzeur
Lemayzeur

Reputation: 8525

The presence of __init__.py tells Python to consider it as a Package, but in order to let Django find your models for Migration and find it well, you should import all your models stuff in __init__.py

Keep the structure like it was:

app/models/__init__.py
app/models/first_model.py
app/models/second_model.py

__init__.py

from .first_models import *
from .second_models import *

Upvotes: 6

Fuhrmanator
Fuhrmanator

Reputation: 12882

In the Cookbook there is an example using only the name of the class (model) and not the app part:

first_model = models.ForeignKey('FirstModel')

Upvotes: 0

Related Questions