Django queryset过滤模型属性与其他模型属性

时间:2015-04-28 08:42:40

标签: python django django-queryset

我不知道我是否清楚这个问题标题,但是,这是我的问题:

我有这个模型,它只是一个事务模型:

class InstanceItemEvaluation(models.Model):
    instance = models.ForeignKey(Instance)
    item = models.ForeignKey(InstanceItem)
    user = models.ForeignKey(User)
    factor = models.ForeignKey(Factor)
    measure = models.ForeignKey(Measure)
    measure_value = models.ForeignKey(MeasureValue, null=True, blank=True)
    evaluated_at = models.DateTimeField(null=True, blank=True)

这是我必须运行的查询,只能从数据库中检索有效值:

@staticmethod
def get_user_evaluations_by_instance(user, instance):
    qs = InstanceItemEvaluation.objects.filter(
        user=user, 
        instance=instance, 
        factor__is_active=True, 
        measure__is_active=True).exclude(
        factor__measure=None)
    return qs

查询集说明了一切,我只是过滤用户,工作实例等等。此查询集输出此SQL:

SELECT "workspace_instanceitemevaluation"."id", 
       "workspace_instanceitemevaluation"."instance_id", 
       "workspace_instanceitemevaluation"."item_id", 
       "workspace_instanceitemevaluation"."user_id", 
       "workspace_instanceitemevaluation"."factor_id", 
       "workspace_instanceitemevaluation"."measure_id", 
       "workspace_instanceitemevaluation"."measure_value_id", 
       "workspace_instanceitemevaluation"."evaluated_at" 
  FROM "workspace_instanceitemevaluation" 
 INNER JOIN "measures_measure" ON ( "workspace_instanceitemevaluation"."measure_id" = "measures_measure"."id" ) 
 INNER JOIN "factors_factor" ON ( "workspace_instanceitemevaluation"."factor_id" = "factors_factor"."id" ) 
 WHERE ("measures_measure"."is_active" = True 
   AND "workspace_instanceitemevaluation"."user_id" = 1 
   AND "factors_factor"."is_active" = True 
   AND "workspace_instanceitemevaluation"."instance_id" = 5 
   AND NOT ("factors_factor"."measure_id" IS NULL));

到目前为止一切顺利。但是现在我需要在查询中加上这个子句:

   AND "factors_factor"."measure_id" = "measures_measure"."id"

这意味着我只想查找当前与我的因素相关的度量值。无论如何,我试图做这样的事情(看看最后的过滤器):

@staticmethod
def get_user_evaluations_by_instance(user, instance):
    qs = InstanceItemEvaluation.objects.filter(
        user=user, 
        instance=instance, 
        factor__is_active=True, 
        measure__is_active=True).exclude(
        factor__measure=None).filter(
        factor__measure=measure)
    return qs

但这甚至没有意义。现在我有点卡住,无法找到解决方案。当然,这是我可以做的事情迭代结果并删除我不需要的结果。但我想弄清楚是否有可能使用Django queryset API实现我提到的SQL查询。

1 个答案:

答案 0 :(得分:1)

我不确定它是否适用于这种情况,但通常您可以使用F()个对象。

from django.db.models import F
qs = InstanceItemEvaluation.objects.filter(
    user=user, 
    instance=instance, 
    factor__is_active=True, 
    measure__is_active=True).exclude(
    factor__measure=None).filter(
    factor__measure=F('measure_id'))