When creating a reusable app, should I put all models I define into single file models.py
or can I group the models into several files like topic1.py
, topic2.py
?
Please describe all reasons pro and contra.
The models
submodule is special in that it is automatically imported at a specific time during the initialization process. All your models should be imported at this time as well. You can't import them earlier than that, and importing them later may cause errors.
You can define your models in a different module, but you should always import all your models into your models.py
or models/__init__.py
. E.g.:
# models/topic1.py
class Topic1(models.Model):
...
# models/__init__.py
from .topic1 import Topic1
If you import each model into models.py
or models/__init__.py
, that also allows you to import all the models directly from that file. In the example, that means that you can import Topic1
from myapp.models
, not just from myapp.models.topic1
. This way you can keep your models organized across multiple files without having to remember each model's precise location whenever you need to import them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With