iskorum
iskorum

Reputation: 1137

How can i group objects according to related objects attribute in django

I have these two models;

class Point(models.Model):
    point       = models.IntegerField()
    description = models.CharField("Action", max_length=128)

class PointLog(models.Model):
    user   = models.ForeignKey('users.User', verbose_name ="Related User")
    point  = models.ForeignKey(Point)
    date   = models.DateTimeField(default = datetime.datetime.now())

The Point objects are static. I mean they don't change dynamically, it shows which action brings how many points. And PointLog objects show user's actions. A user can accomplish same action more than one.

I want to group PointLog objects according to user actions and sum each different action's point

Help :)

Sample Point Objects;

description      point
-----------------------
make comment     5
add photo        20
add video        50

Sample PointLog Objects;

User        point         date
------------------------------
user1    make comment     ....
user1    make comment     ....
user1    add photo        ....
user1    add photo        ....
user1    add photo        ....
user1    add photo        ....
user1    add video        ....
user1    add video        ....
user1    add video        ....

Sample result;

user1s action;
  make comment 10 points gained
  add photo    80 points gained
  add video    150 points gained

Upvotes: 2

Views: 263

Answers (2)

schacki
schacki

Reputation: 9533

PointLog.objects.all().values('user','point__description').annotate(points_gained=Sum('point__point'))

Upvotes: 1

Sergey Lyapustin
Sergey Lyapustin

Reputation: 1937

use this:

result = PointLog.objects.all().values("user", 'point').annotate(num=Count("pk"))

Upvotes: 0

Related Questions