When I list points I want to add up all the points for a user. In my template I’ll like to just call something like ‘points.total_points’. Below is what I have so far, I would like to keep this all in my model if possible. Could someone help explain how to acheive this?
Thanks
model.py
class PointsManager(models.Manager):
def points_list(self,thisUser):
list = Points.objects.filter(user=thisUser)
return list
class Points (models.Model):
user = models.ForeignKey(User)
points = models.IntegerField(verbose_name=("Points"), default=0)
created = models.DateTimeField(("Created at"), auto_now_add=True)
updated = models.DateTimeField(verbose_name=("Updated at"), auto_now=True)
objects = PointsManager()
class Meta:
verbose_name = ('Point')
verbose_name_plural = ('Points')
view.py
@login_required
def history(request):
thisPoints = Points.objects.points_list(request.user)
context = {'points':thisPoints}
return render_to_response('points/history.html', context, context_instance=RequestContext(request))
There’re a couple of things that could be done:
1) make request available in templates:
add
common.core.middleware.RequestMiddlewaretoMIDDLEWARE_CLASSESso that you could just write
request.userto access User model2) add total_points method to User model (it can be done in various ways,
contribute_to_classorUserProfileto name two of them)so that you could write
request.user.total_pointsin a template3) cache
total_pointsto avoid a database hit every time the page is viewed:3a) either use standard django caching framework,
or if you want the displayed value to change immediately after it has been changed in the database,
3b) update the value manually when a new
Pointinstance is created/modified/deleted via django signals