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

前端 未结 9 1074
广开言路
广开言路 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 03:11

    ipython console does a deep reload with each reload() expression; and of course adds a lot of other useful stuff.

    0 讨论(0)
  • 2020-11-28 03:14

    I wasn't able to get any of the above solutions to work, but I did come up with a workaround for reloading any other non-models module in my django project (e.g. a functions.py or views.py module).

    1. Create a file called reimport_module.py. I stored it in the local/ folder of my django project on my dev machine.

      # Desc: Imports the module with the name passed in, or imports it for first
      #       time if it hasn't already been imported.
      #
      #       Purpose of this script is to speed up development of functions that
      #       are written in an external editor then tested in IPython.
      #
      #       Without this script you have to exit & reenter IPython then redo
      #       import statements, definitions of local variables, etc.
      #
      #       Note: doesn't work for Django models files, because Django caches
      #       them in a structure called AppCache.
      #
      # Args: module to reload (string)
      
      import sys
      
      module_to_reload = sys.argv[1]
      
      # Attempt to pop module
      try:
          sys.modules.pop(module_to_reload)
          print 'reimporting...'
      except KeyError:
          print 'importing for first time...'
      
      # (re)import module
      import_str = 'from {0} import *'.format(module_to_reload)
      exec(import_str) 
      
    2. Launch shell plus (which uses an embedded IPython shell):

      python manage.py shell_plus

    3. Use the following to import the module you are developing:

      %run local/reimport_module.py 'your.module'

    4. Use IPython to test functions in your module.

    5. Make changes to the module in an external editor.
    6. Use the following to reimport the module without having to exit & reenter IPython:

      %run local/reimport_module.py 'your.module'

      Note: this command was already used in step 3, so you can type %run then the up arrow to autocomplete it.

    0 讨论(0)
  • 2020-11-28 03:16

    Assuming your project is set up this way

    • project name : bookstore
    • app name : shelf
    • model name : Books

    first load

    from bookstore.shelf.models import Books
    

    subsequent reloads

    import bookstore;reload(bookstore.shelf.models);from bookstore.shelf.models import Books
    
    0 讨论(0)
提交回复
热议问题