开发者

For all my foreignKeys, should i use User or UserProfile in Django?

Here is the sutuation i hit.

I have both 开发者_运维百科User and ProfileUser. I would like to add additional logic to the model and since I can't add it to the Django User model, I have to add it to the ProfileUser. Currently all my models however have ForeignKey(User). Should I keep them like that or should I user ForeignKey(UserProfile) on my other models?

Example for my view if I keep the ForeignKey(User):

class myview(request):
    user = request.user
    userProfile = user.get_profile()
    neededStuff = userProfile.get_needed_stuff()

and then in the UserProfile model:

def get_needed_stuff(self):
    user= self.user # Or actually, is this right 
    goals = Goal.objects.get(<conditions that i wont bother writing here>)
    return goals

So for this case, and for further development of the site, which foreign key should i use?


I think You should use User. UserProfile should be custom and can differ on each project. So if you will use same code for another project you can probably fail because of that. Also it is always easy to get user object in code and from that you have no problems to get profile user.get_profile() as you show (and profile is not always needed). So ingeneral I think it will be easier to use other modules and passing them just user object (or id) and not the profile.

What is also could be the solution - write your own class which will be responsible for the users. Just write methods to return profile, return stuff_needed or whatever you want and everything just by passing user object and additional parameters about what you want.

So in short, I'm for using User for Foreign keys, because in my opinion it just more logical, while the User model is always the main one (you always have it) and UserProfile is just extension.

Ignas


If you just want all the goals belonging to a specific user add a foreign key to User in your Goal model.

class Goal(models.Model):
    user = models.ForeignKey(User)

def myview(request):
    goals = Goal.objects.filter(user=request.user)

Or alternately save all the goals for a user on your UserProfile model and do

def myview(request):
    user_profile = user.get_profile()
    goals = user_profile.goals

...or use a method to do processing to calculate them

goals = user_profile.calculate_goals()


I've been pondering the same thing myself for one of my sites but i decided to use UserProfile rather than User. Not sure if its the right decision but it just seems more flexible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜