Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving django models into their own files

In the name of maintainability, I moved some of my larger models to their own files. So before i had this:

app/
  models.py

and now I have this:

app/
  models/
    __init__.py
    model_a.py
    model_b.py

This works fine, but when I use manage.py to do sync db, it doesn't create a table for these models anymore.

Am I forgetting something?

Thanks,

like image 763
Goro Avatar asked Feb 16 '12 21:02

Goro


People also ask

Can I move a Django model from one app to another?

Moving a Django model to another app by copying the data has its advantages and disadvantages. Here are some of the pros associated with this approach: It’s supported by the ORM: Performing this transition using built-in migration operations guarantees proper database support. It’s reversible: Reversing this migration is possible if necessary.

How do I add models to my Django project?

Once you have defined your models, you need to tell Django you’re going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py.

How do I set the default file storage system in Django?

Django’s default file storage is given by the DEFAULT_FILE_STORAGE setting; if you don’t explicitly provide a storage system, this is the one that will be used. See below for details of the built-in default file storage system, and see How to write a custom storage class for information on writing your own file storage system.

What file format does Django use?

Internally, Django uses a django.core.files.File instance any time it needs to represent a file. Most of the time you’ll use a File that Django’s given you (i.e. a file attached to a model as above, or perhaps an uploaded file).


2 Answers

Models must be found in module named app.models where app is an app name. So you should write in app/models/__init__.py file

 from model_a import * 
 from model_b import * 

In Django < 1.7

Note fron django 1.7 onwards this is not neccessary.

Moreover --- (that's what I had problem with) you will have to manually update app_label attribute for your models, so write:

 __all__ = ["ModelA", "ModelA1"]

 class ModelA(models.Model):
      class Meta: 
          app_label = 'your_app'

without it app will be set incorrectly by django.

If you are afreid that from model_a import * are evil you allways can set up __all__ attributes in all modules.

like image 191
jb. Avatar answered Oct 22 '22 11:10

jb.


You need to set Meta.app_label for each of the models to the app name where it belongs and make sure they are imported from models/__init__.py.

You can have a look here for more details: https://code.djangoproject.com/wiki/CookBookSplitModelsToFiles

like image 28
Jakub Roztocil Avatar answered Oct 22 '22 11:10

Jakub Roztocil