How do you reload a Django model module using the interactive interpreter via “manage.py shell”?

前端 未结 9 1089
广开言路
广开言路 2020-11-28 02:14

I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:

How do I unload (reload

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 02:50

    Enable IPython autoreload extension before importing any code:

    %load_ext autoreload
    %autoreload 2
    

    I use it with the regular django shell and it works perfectly, although it does have some limitations:

    *Caveats:

    Reloading Python modules in a reliable way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work:

    • Functions and classes imported via ‘from xxx import foo’ are upgraded to new versions when ‘xxx’ is reloaded.
    • Methods and properties of classes are upgraded on reload, so that calling ‘c.foo()’ on an object ‘c’ created before the reload causes the new code for ‘foo’ to be executed.

    Some of the known remaining caveats are:

    • Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only).
    • Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded.
    • C extension modules cannot be reloaded, and so cannot be autoreloaded.*

    source: https://ipython.org/ipython-doc/3/config/extensions/autoreload.html#caveats

    Another great option is to write your code in a separate script and send it to django shell, like this:

    manage.py shell < my_script.py
    

提交回复
热议问题