如何在Django模型查询中添加比较模型本身的两个字段的条件

时间:2013-06-11 09:39:22

标签: python django django-models

如标题所述,在Django中:

假设我有一个型号名称QuestionRecord,有两个字段:full_scoreactual_score。 我想实现SQL:

select * from QuestionRecord as QR where QR.full_score!=QR.actual_score.

也许使用原始sql是可以的,但我想像这样实现它:

class QuestionRecord_QuerySet(models.query.QuerySet):
    def incorrect(self):# Find out those whose full_score and actual_score are not equal
        return self.filter(...) # **What should I write here??**

class QuestionRecord_Manager(models.Manager):
    def get_query_set(self):
        return QuestionRecord_QuerySet(self.model)

class QuestionRecord(models.Model):
    objects = QuestionRecord_Manager()

有什么办法吗?

1 个答案:

答案 0 :(得分:1)

当然,这就是"F" object的用途!

from django.db.models import F

# snip

    return self.exclude(full_score = F('actual_score'))

在此使用QuerySet.exclude,因为您不想获得匹配的结果。

如果您真的想使用QuerySet.filter,可以使用否定的"Q" objectself.filter(~Q(full_score = F('actual_score')))