针对其他模型属性的 Django 查询集过滤器模型属性

Django queryset filter model attribute against other model attribute

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

我有这个模型,它只是一个交易模型:

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"

这意味着我只在寻找当前与我的因素相关联的度量值。无论如何,我尝试做这样的事情(看看最后的 filter):

@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 查询集 API.

的这个 SQL 查询

我不确定它是否适用于这种情况,但通常您可以为此使用 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'))