Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should django manager code live?

Tags:

This is a pretty simple django patterns question. My manager code usually lives in models.py, but what happens when models.py is really huge? Is there any other alternative pattern to letting your manager code live in models.py for maintainability and to avoid circular imports?

A question may be asked as to why models.py is so huge, but let's just assume it's size and breadth of utility is justified.

like image 307
eculver Avatar asked Dec 10 '09 19:12

eculver


People also ask

Where are Django models located?

Since Django only looks for models under the Python path <app>. models , you must declare a relative import in the main models.py file -- for each of the models inside sub-folders -- to make them visible to the app.

What is the use of manager in Django?

A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application. The way Manager classes work is documented in Making queries; this document specifically touches on model options that customize Manager behavior.

What is the name of the default manager Django adds to every model class?

By default, Django adds a Manager with the name "objects" to every Django model class.


2 Answers

I prefer to keep my models in models.py and managers in managers.py (forms in forms.py) all within the same app. For more generic managers, I prefer to keep them in core.managers if they can be re-used for other apps. In some of our larger apps with models/modelname.py that will contains a manager and the model code which doesn't seem bad.

like image 111
Jeff Triplett Avatar answered Oct 20 '22 03:10

Jeff Triplett


Your best bet with a large set of models is to use django modules to your advantage, and simply create a folder named models. Move your old models.py into this models folder, and rename it __init__.py. This will allow you to then separate each model into more specific files inside of this model folder.

You would then only need to import each model into your __init__.py's namespace.

So, for instance, you might want to separate it into:

yourapp/     models/         __init__.py # This file should import anything from your other files in this directory         basic.py # Just an example name         morespecificmodels.py # Just an example name         managers.py # Might want to separate your manager into this 

Then your __init__.py can just be:

from basic import * # You should replace * with each models name, most likely. from managers import YourManager # Whatever your manager is called. 

This is the structure that I use when my model files get huge, however I try to separate things into more pluggable apps as often as possible - so this is rarely used by me.

Hope this helps.

like image 33
monokrome Avatar answered Oct 20 '22 03:10

monokrome