Unfortunately, according to the Django ticket for this (https://code.djangoproject.com/ticket/13914) it seems that we aren't going to get this functionality built-in any time soon. However, after many hours of inspection in the Django source, I think I have found a solution...
1. In Django 1.3 the User model already has it's own UserManager, so we must update that instead of overwriting it. This makes adding natural keys for Users much easier.
2. The ValidationError is because it's not even trying to use the natural keys- this code uses private fields like _default_manager, which were initialised before the manager was replaced. In the end, since we are only adding a method and nothing else, the most appropriate way to fix this is to change the __class__ of the objects member in Group.
3. I don't appear to need add_to_class(), but YMMV. An example would be good.
def uget_by_natural_key(self, username):
return self.get(username=username)
def gnatural_key(self):
return self.name
def unatural_key(self):
return self.username
class GroupManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
UserManager.get_by_natural_key = uget_by_natural_key
Group.objects.__class__ = GroupManager
User.natural_key = unatural_key
Group.natural_key = gnatural_key
For reference, I put this code in models.py.
Disclaimer: This kind of hackery may have serious side-effects, especially since Django has done a lot of initialisation by the time we get to this point.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/v5rH2CqDHHoJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment