13

I am learning Django. My background is from PHP and Java with experience using Model View Controller frameworks. I have always had a seperate file for each of my views, models, and templates - but the Django tutorial only mentions having one views.py and models.py.

That seems to be okay if you have a small application — what if you would like to organise your views and models by their purpose? For example, a Projects view and a Milestones view. I would hope that you would not have to create another Python package (app) for each view module:

python manage.py startapp projects

python manage.py startapp milestones

I can assume that you can have a milestones.py and a projects.py for your views and models instead of a generic views.py and models.py? Then models can be imported where necessary into the views, and requests routed to specific views?

1 Answer 1

26

There is no problem with having multiple files containing views and models.

In fact all you need is module views and module models. In python the module is either file that ends with .py or folder that contains file __init__.py.

The app can look something like:

app_folder
    - views
    |    - __init__.py
    |    - some_view.py
    |    - some_other_view.py
    - models
    |    - __init__.py
    |    - some_model.py
    |    - some_other_model.py

The models/__init__.py should look similar to code below (for submodules to be looked up by django at all).

from some_model import SomeModel
from some_other_model import SomeOtherModel

The only difference from the common approach is to have app_label defined in models:

class SomeModel(models.Model):
    class Meta:
        app_label = 'app_folder'

Check out the related doc entry.

Update:

The development version docs say you won't have to define app_label in this case any more starting with 1.7 release.

Afterword:

In fact if you need to do that it usually means your app is too big and you should split it into several apps. Most people who come to django are afraid of having many small apps. The more third party apps you read through the more you realize app should solve one and only one problem. In your example having app milestones seems perfectly legit.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.