Wednesday, July 31, 2013

Looking for the right way to specialize the User model

I'm using Django 1.5 and I needed an api to control the addition of users and the management of users on those groups. Django's rest framework proved a good starting point but I hit issues with the ManyToMany relation groups which means that there is no model for the user_group which in turn complicated the API. I worked around this fairly easily with the following code:

from django.db import models  from django.contrib.auth.models import User, UserManager, Group    class UserGroup(models.Model):      user = models.ForeignKey(User)      group = models.ForeignKey(Group)      class Meta:  	# auth_user_groups is created by the ManyToMany relation field  	# in the contrib.auth.models User model  	managed = False  	db_table = 'auth_user_groups'    # Add an easy way to get at this from the User objects  def get_user_groups(self):      return UserGroup.objects.filter(user=self)  User.add_to_class('get_user_groups', get_user_groups)  

This handles the problem by allowing the API to have convenient usergroup urls and endpoints but I don't like using 'add_to_class'. I really just want a specialized user class but I could not get the following to work:

class APIUser(User):      objects = UserManager()      class Meta:  	managed = False  	db_table = 'auth_user'        def get_user_groups(self):  	return UserGroup.objects.filter(user=self)  

Sadly, it fails with, for example, "Unknown column 'auth_user.user_ptr_id' in 'where clause'" if I try to save a newly created APIUser.

Am I barking up the wrong tree or just missing something obvious?



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment