Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using other file names than models.py for Django models?

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.

like image 277
porton Avatar asked Sep 13 '25 10:09

porton


1 Answers

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.

like image 162
knbk Avatar answered Sep 14 '25 23:09

knbk