Can i share models in different files in django

Currently, all my models are in models.py. Ist is getting very dirty. Can I have a separate file, for example base_models.py , so that I put my main models there that I don’t want to touch

Also, the same case for submissions is placed in a separate folder, and does not develop a new application

+8
python django django-models
source share
4 answers

Yes, it is doable. It is not particularly beautiful, though:

make models a module, so your directory structure looks like this:

 - models |- __init__.py |- some_model.py |- some_other_model.py |- ... 

now the magic is in __init__.py and some small additions to the models. __init__.py :

 from some_model import SomeModel from some_other_model import SomeOtherModel __all__ = [ 'SomeModel', 'SomeOtherModel', ] 

some_model.py:

 class SomeModel(models.Model): class Meta(object): app_label = 'yourapplabel' db_table = 'yourapplabel_somemodel' 
+10
source share

All that acjohnson55 said, plus the fact that you need to specify the app_label attribute in every Meta class.

Link to the actual example on github: https://github.com/stefanfoulis/django-filer/tree/develop/filer/models

+2
source share

Yes, just create a folder called models and in this folder put all your shared model files. You need to put a file called __init__.py in the models folder so that it is considered the models module. In __init__.py use from ... import ... to put the names that you want to get directly into yourapp.models , otherwise you will have to import them as yourapp.models.base_model or the other submodule name that you are using.

In addition, in each model you will need to add the Meta app_label = 'yourapp' attribute to make sure your models are recognized as part of the application.

0
source share

you can separate the model file as follows:
------- models /
-------------- init .py
-------------- usermodels.py
--------------othermodel.py

in init .py:
--------------- from import usermodels *
--------------- from importing other models *
and in * models.py add the META class:
-------- Meta class:
-------------- app_label = 'appName'

0
source share

All Articles