How to monkey patch Django?
I came upon this post on monkey patching Django:
from django.contrib.auth.models import User
User.add_to_class('openid', models.CharField(max_length=250,b开发者_StackOverflow社区lank=True))
def get_user_name(self):
if self.first_name or self.last_name:
return self.first_name + " " + self.last_name
return self.username
User.add_to_class("get_user_name",get_user_name)
I understand that this isn't ideal and it's better to add fields and functions to User
through a separate model Profile
.
With that said, I just want to understand how this would work:
Where would I put the monkey patching code?
When is the code run -- just once? once per Python interpreter startup? once per request?
Presumably I'd still need to change the DB schema. So if I dropped the table
User
and ran./manage.py syncdb
, wouldsyncdb
"know" that a new field has been added toUser
? If not how do I change the schema?
put the file monkey_patching.py
in any of your apps
and import it in app's __init__.py
file. ie:
app/monkey_patching.py
#app/monkey_patching.py
from django.contrib.auth.models import User
User.add_to_class('openid', models.CharField(max_length=250,blank=True))
def get_user_name(self):
if self.first_name or self.last_name:
return self.first_name + " " + self.last_name
return self.username
User.add_to_class("get_user_name",get_user_name)
app/__init__.py
#app/__init__.py
import monkey_patching
You could put it anywhere, but it's common to see this kind of stuff linked in the settings file (or even the urlconf). Anywhere you could put a signal might also be appropriate. This code should really be slightly more intelligent - often files get imported more than once and there's not a lot you can do about it, so you can run into problems if you try to run code like this multiple times.
The code needs to be executed at least once for each python process.
Yes you would need to change the DB by hand. Syncdb probably wouldn't catch the change (I haven't looked closely at the code), but there might be some places you could put the code that would work.
You seem to already know that this is a terrible, horrible thing to do and should never be done for real code, so I won't belabor that point. Doing this kind of thing is a fantastic way to generate really difficult to find bugs in your code, in addition to code that may not work in future versions of Django.
Also, it won't work well with South, which you should be using.
Using both @suhailvs and @Paul McMillan's suggestions I added a patch.py
file to the root of my app, and inside the app's apps.py
called my patched in the ready
signal:
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = "MyApp"
def ready(self):
"""
Called when the app is ready.
"""
from .patch import patch_func
patch_func()
The AppRegistryNotReady: Apps aren't loaded yet.
happens because of the import, not the function call, so it must be inside the function.
精彩评论