根据django中的模型字段过滤queryset中的唯一记录

时间:2014-09-02 08:16:29

标签: django django-models filter django-queryset

我有一个类似下面的模型

class SafetyRead(models.Model):
    name = models.CharField(max_length=256)
    accession_number =  models.CharField(max_length=256)
    data = models.CharField(max_length=256)
    approved = models.BooleanField()
    radiologist = models.BooleanField() 

    def __unicode__(self):
        return 'SafetyRead - %s'%self.accession_number

通常当我以下面的方式完成搜索时,我得到了结果

查询

SafetyRead.objects.filter(approved=False,radiologist=False)

结果

[<SafetyRead: SafetyRead - 2983>, <SafetyRead: SafetyRead- 2582>, <SafetyRead: SafetyRead - 2583>, <SafetyRead: SafetyRead - 2522>, <SafetyRead: SafetyRead - 2522>]

从上面的查询结果可以看出,最后两个记录与字段accession_number重复,即2522

所以我想根据字段accession_number以相同的查询集格式过滤独特的SafetyRead对象记录,如下所示(删除重复的accession_number 2522记录后)

[<SafetyRead: SafetyRead - 2983>, <SafetyRead: SafetyRead- 2582>, <SafetyRead: SafetyRead - 2583>, <SafetyRead: SafetyRead - 2522]

那么如何过滤呢?

1 个答案:

答案 0 :(得分:0)

我相信你正在寻找distinct

尝试:

SafetyRead.objects.filter(approved=False,radiologist=False).distinct()