Where should django manager code live?

前端 未结 4 2038
无人及你
无人及你 2021-02-01 18:15

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 patt

4条回答
  •  不思量自难忘°
    2021-02-01 18:50

    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.

提交回复
热议问题