Django模型:聚合过滤器

时间:2012-12-25 11:40:41

标签: python django django-models

在我看来,我得到了points_total,但它返回的所有点都不同于当前用户过滤的points_list。

问题:

1)如何按用户过滤'def points_total',如'points_list'

model.py

class PointsManager(models.Manager):

    def points_list(self,thisUser):
        list = Points.objects.filter(user=thisUser)
        return list

    def points_total(self,thisUser):
        return Points.objects.aggregate(models.Sum('points'))


class Points (models.Model):

    statusOptions = (
        (0, 'Pending'),
        (1, 'Added'),
        (2, 'Deducted'),
        (3, 'Processing'),
        )

    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)
    status = models.IntegerField(default=0, choices=statusOptions)

    objects = PointsManager()



    class Meta:
      verbose_name = ('Point')
      verbose_name_plural = ('Points')

1 个答案:

答案 0 :(得分:2)

首先,我认为你的两个职能部门都不需要经理,你可以直接通过查询模型来实现。

point_list功能

的替代方案
points_list = Points.objects.filter(user=request.user)

points_total功能

的替代方案
points = Points.objects.filter(user=request.user) \
                       .aggregate(total_points=models.Sum('points'))