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:
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?