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

前端 未结 9 1090
广开言路
广开言路 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:56

    My solution on 2016 (in future it may be changed)

    1.Install django_extension

    2.Add next settings:

    SHELL_PLUS = 'ipython'
    
    IPYTHON_ARGUMENTS = [
        '--ext', 'autoreload',
    ]
    

    3.Run shell

    ./manage.py shell_plus
    

    See results:

    model example

    class Notification(models.Model):
    
        ........
    
        @classmethod
        def get_something(self):
    
            return 'I am programmer'
    

    In shell

    In [1]: Notification.get_something()
    Out[1]: 'I am programmer'
    

    Made changes on model

    @classmethod
        def get_something(self):
    
            return 'I am Python programmer'
    

    In shell

    # shell does not display changes
    In [2]: Notification.get_something()
    Out[2]: 'I am programmer'
    

    In shell. This is a magic

    # configure extension of ipython
    In [3]: %autoreload 2
    

    In shell

    # try again - all worked
    In [4]: Notification.get_something()
    Out[4]: 'I am Python programmer'
    

    Made changes again

        @classmethod
        def get_something(self):
    
            return 'I am full-stack Python programmer'
    

    In shell

    # all worked again
    In [5]: Notification.get_something()
    Out[5]: 'I am full-stack Python programmer'
    

    Drawback: 1. Need manually run code

    %autoreload 2

    since django_extension 1.7 has not support for run arbitrary code. May be in future release it has this feature.

    Notes:

    1. Django 1.10
    2. Python 3.4
    3. django_extension 1.7.4
    4. Based (primary) on https://django-extensions.readthedocs.io/en/latest/shell_plus.html and http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html
    5. Caution. It is may be produce an error, if you try change a code where used super().

提交回复
热议问题