Django仅对聚合/注释进行过滤

时间:2014-11-26 16:40:42

标签: python django database django-models django-queryset

我正在尝试构建一个相当复杂的Django查询,但我没有取得多大进展。我希望这里的一些巫师可以帮助我吗?

我有以下型号:

class Person(models.Model):
    MALE = "M"
    FEMALE = "F"
    OTHER = "O"
    UNKNOWN = "U"
    GENDER_CHOICES = (
            (MALE, "Male"),
            (FEMALE, "Female"),
            (UNKNOWN, "Other"),
    )


    firstName       = models.CharField(max_length=200, null=True, db_column="firstname")
    lastName        = models.CharField(max_length=200, null=True, db_column="lastname")

    gender          = models.CharField(max_length=1, choices=GENDER_CHOICES, default=UNKNOWN, null=True)
    dateOfBirth     = models.DateField(null=True, db_column="dateofbirth")
    dateInService   = models.DateField(null=True, db_column="dateinservice")
    photo           = models.ImageField(upload_to='person_photos', null=True) 

class SuccessionTerm(models.Model):
    originalName    = models.CharField(max_length=200, null=True, db_column="originalname")
    description     = models.CharField(max_length=200, blank=True, null=True)
    score           = models.IntegerField()

class Succession(model.Model):
    position    = models.ForeignKey(Position, to_field='positionId', db_column="position_id")
    employee    = models.ForeignKey(Employee, to_field='employeeId', db_column="employee_id")
    term        = models.ForeignKey(SuccessionTerm)

class Position(models.Model):
    positionId      = models.CharField(max_length=200, unique=True, db_column="positionid")
    title           = models.CharField(max_length=200, null=True)
    # There cannot be a DB constraint, as that would make it impossible to add the first position.
    dottedLine      = models.ForeignKey("Position", to_field='positionId', related_name="Dotted Line",
                                        null=True, db_constraint=False, db_column="dottedline_id")
    solidLine       = models.ForeignKey("Position", to_field='positionId', related_name="SolidLine", 
                                        null=True, db_constraint=False, db_column="solidline_id")
    grade           = models.ForeignKey(Grade)
    businessUnit    = models.ForeignKey(BusinessUnit, null=True, db_column="businessunit_id")
    functionalArea  = models.ForeignKey(FunctionalArea, db_column="functionalarea_id")
    location        = models.ForeignKey(Location, db_column="location_id")

class Employee(models.Model):
    person                = models.OneToOneField(Person, db_column="person_id")
    fte                   = models.IntegerField(default=100)
    dataSource            = models.ForeignKey(DataSource, db_column="datasource_id")
    talentStatus          = models.ForeignKey(TalentStatus, db_column="talentstatus_id")
    retentionRisk         = models.ForeignKey(RetentionRisk, db_column="retentionrisk_id")
    retentionRiskReason   = models.ForeignKey(RetentionRiskReason, db_column="retentionriskreason_id")
    performanceStatus     = models.ForeignKey(PerformanceStatus, db_column="performancestatus_id")
    potential             = models.ForeignKey(Potential, db_column="potential_id")
    mobility              = models.ForeignKey(Mobility, db_column="mobility_id")
    currency              = models.ForeignKey(Currency, null=True, db_column="currency_id")
    grade                 = models.ForeignKey(Grade, db_column="grade_id")
    position              = models.OneToOneField(Position, to_field='positionId', null=True, 
                                                 blank=True, db_column="position_id")
    employeeId            = models.CharField(max_length=200, unique=True, db_column="employeeid")
    dateInPosition        = models.DateField(null=True, db_column="dateinposition")

现在,我想要的是每个员工获得职位名称,人名,以及每个继任期限(其中有三个)该雇员在继任表中的位置,以及每个雇员在后继者表中出现的次数。最重要的是,我想在一个单一的查询(或更具体地说,一个Django ORM语句)中完成所有这些,因为我是以分页方式执行此操作,但我希望能够在任何这些专栏!

到目前为止,我有这个:

emps = Employee.objects.all()
       .annotate(ls_st=Count('succession__term'))
       .filter(succession__term__description="ShortTerm")
       .order_by(ls_st)
       .prefetch_related('person', 'position')[lower_limit:upper_limit]

这只是继承术语之一,我想通过添加更多注释调用将其扩展到所有术语。 我的问题是过滤器调用适用于整个查询。我想只过滤Count调用。

我尝试过像Count(succession__term__description'="ShortTerm")这样的事情,但这不起作用。还有其他办法吗?

非常感谢您提前, 的问候,

莱纳斯

1 个答案:

答案 0 :(得分:0)

那么你想要的是每种不同类型的继承____的计数?这是非常复杂的,我认为你现在不能使用内置的django orm。 (除非您进行了.extra()查询)

在django 1.8中,我相信您可以使用新的查询表达式(https://docs.djangoproject.com/en/dev/releases/1.8/#query-expressions)来完成。但当然1.8还没有发布,所以这对你没有帮助。

与此同时,您可以使用非常方便的django-aggregate-if包。 (https://github.com/henriquebastos/django-aggregate-if/https://pypi.python.org/pypi/django-aggregate-if

使用django-aggregate-if,您的查询可能如下所示:

emps = Employee.objects.annotate(
        ls_st=Count('succession__term', only=Q(succession__term__description="ShortTerm")),
        ls_lt=Count('succession__term', only=Q(succession__term__description="LongTerm")), # whatever your other term descriptions are.
        ls_ot=Count('succession__term', only=Q(succession__term__description="OtherTerm"))
    )
    .order_by('ls_st')
    .prefetch_related('person', 'position')[lower_limit:upper_limit]

免责声明:我从未使用过django-aggregate-if,所以我不完全确定这是否可行,但根据自述文件,似乎应该这样。