0

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?

4

1 回答 1

1

就个人而言,我不打扰get_profile()助手。User我只是在我的 UserProfile 中使用一对一的字段并设置related_name='projname_profile'.

然后,您可以使用 ORM 魔法在单个请求中获取所有内容(需要注意的是,我认为 select_related 仅在 Django 1.2 之后选择反向 1-1,但也许它被反向移植了......):

user = User.objects.select_related().get(pk=1)
profile = user.projname_profile   # or just call it inline
于 2010-03-30T21:48:24.227 回答