views:

94

answers:

1

I have been refactoring an app that had customized the standard User model from django.contrib.auth.models by creating a UserProfile and defining it with AUTH_PROFILE_MODULE.

The problem is the attributes in UserProfile are used throughout the project to determine what the User sees.

I had been creating tests and putting in this type of statement repeatedly:

user = User.objects.get(pk=1)
user_profile = user.get_profile()

if user_profile.karma > 10:
    do_some_stuff()

This is tedious and I'm now wondering if I'm violating the DRY principle.

Would it make more sense to create a custom UserManager that automatically loads the UserProfile data when the user is requested.

I could even iterate over the UserProfile attributes and append them to the User model. This would save me having to update all the references to the custom model attributes that litter the code.

Of course, I'd have to reverse to process for to allow the User and UserProfile models to be updated correctly.

Which approach is more Django-esque?

+1  A: 

Personally, I don't bother with the get_profile() helper. I just use a one-to-one field to User in my UserProfile and set related_name='projname_profile'.

Then you can use the ORM magic to get everything in a single request (with the caveat that I think select_related only selects the reverse 1-1 in Django 1.2 onwards, but perhaps it was backported...):

user = User.objects.select_related().get(pk=1)
profile = user.projname_profile   # or just call it inline
SmileyChris