Search code examples
pythondjangodjango-modelsmonkeypatching

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,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)

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:

  1. Where would I put the monkey patching code?

  2. When is the code run -- just once? once per Python interpreter startup? once per request?

  3. Presumably I'd still need to change the DB schema. So if I dropped the table User and ran ./manage.py syncdb, would syncdb "know" that a new field has been added to User? If not how do I change the schema?


Solution

  • 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.