Django model definitions can’t be reloaded

I spent way too much time this evening figuring this out.

If you have a models file like this (artificial, but play along):


from django.db import models
from random import random
rand_val = random()

class MyModel(models.Model):
    r = rand_val

After you import MyModel in some other module, you can’t re-load the class definition of MyModel.

You might think that calling reload() on models would do the trick. What actually happens is:

  • models.py is reloaded (the file is executed again)
  • so models.rand_value changes…
  • but models.MyModel.r does not!

Classes that inherit from models.Model seem to be immortal singletons. I tried removing them from sys.modules as arthurk is doing. I tried deleting all references to the variables in my code. The first instance came back every time, even though python was shown to be reloading the module and re-executing the code within.

In most use cases, this is exactly what you want. It usually would be inefficient to have multiple copies of MyModel available in different parts of your code.

Unfortunately, I needed multiple instances for testing purposes. I ended up settling for a less comprehensive testing solution.

Post a Comment

Your email is never published nor shared. Required fields are marked *