如何根据django中的相关对象属性对对象进行分组

时间:2012-08-23 10:59:51

标签: django group-by

我有这两个模型;

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())

Point个对象是静态的。我的意思是他们不会动态变化,它会显示哪个动作会带来多少分。 PointLog对象显示用户的操作。用户可以多次完成相同的操作。

我想根据用户操作对PointLog个对象进行分组,并对每个不同的操作点进行总结

帮助:)

示例点对象;

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

示例PointLog对象;

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        ....

样本结果;

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

2 个答案:

答案 0 :(得分:1)

PointLog.objects.all()。值( '用户', 'point__description')。注释(points_gained = SUM( 'point__point'))

答案 1 :(得分:0)

使用它:

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