【问题标题】:Filter the unique records in queryset based on a model field in django根据 django 中的模型字段过滤查询集中的唯一记录
【发布时间】:2014-10-26 10:46:20
【问题描述】:

我有一个像下面这样的模型

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]

那么如何过滤呢?

【问题讨论】:

  • 两条重复记录中您要保留哪一条? id 大的那个?

标签: django django-models filter django-queryset


【解决方案1】:

我相信你在找distinct

尝试:

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

【讨论】:

  • 但是通过使用distinct 它给了我*** NotImplementedError: DISTINCT ON fields is not supported by this database backend 错误
  • 抱歉,我错过了文档中的某些内容,如果您使用的是 postgres,则只能将字段传递给 distinct。我已经更新了答案。
  • 但是如果我们只使用disticnt(),结果是一样的,因为它会根据id删除重复记录,但是我们想删除包含重复accession_number模型字段值的重复记录
  • 根据不真实的文档For a normal distinct() call, the database compares each field in each row when determining which rows are distinct. For a distinct() call with specified field names, the database will only compare the specified field names.
  • 但我在这里使用 mysql,所以当我使用 distinct('accession_number') 时,它抱怨我上面粘贴的错误,当我使用 SafetyRead.objects.filter(approved=False,radiologist=False).distinct() 时,我仍然得到相同的查询集结果和重复的 @ 987654332@,那现在怎么办?
猜你喜欢
  • 2013-10-10
  • 2015-10-14
  • 2016-07-20
  • 2017-11-22
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多