5
YOu can call the function in your view like rank = personal_rank(reuest.user)
and add rank
to your context then.
I wouldnt call this functions “view”-functions, since they are not dealing with a request nor are they returning a HttoResponce; they are more “helper” functions and also don’t belong to a model if they are dealing with seperate entities (eg. News & Vote). A descent place for them would be eg. utils.py
. You import them from there in your views.py
and call them with the user as parameter (if it’s the actual user it’s request.user
).
It makes sense that you can’t access request
from everywhere, because this forces you to keep more to a mvc-like design, if you need request somewhere you need to pass it on from your original view function!
You should change your last function to:
def personal_rank(user):
personal_rank = calculate_questions_vote(user) + \
calculate_replies(user) + \
calculate_votes(user)
return personl_rank
You could also add this last function to your User or UserProfile model class if you have something like that and then call eg. my_user.personal_rank()
or my_user.get_profile().personal_rank()
.
3
lazerscience gave good explanation for your guestion. I just want to point some possible performance issues.
Please note that calling this method for each User yields with 7 queries. If your case will be showing rank for all users it might take a lot of time. I suggest make some caching (like in StackOverflow). There are many options here, for example you can assign special rank field to a User
model (or UserProfile
if User
is auth.User
) in which you could store precalaculated rank (calculated just after some operation, like News saving or in some scheduled intervals).
- [Django]-Django post_save and south migrations
- [Django]-Django mongodbforms exception when rendering embedded formset management_form
- [Django]-In the Django admin is it possible to separate models into sub-models based on groups?