使用.distinct()时,Django ORM多次返回相同的值

时间:2016-04-27 18:48:15

标签: python django django-orm

在一组对象上使用.distinct()时,会反复重复相同的值,这会影响使用.distinct()的目的

我正在进行的项目的一个例子:

In [5]: Section.objects.filter(module=15).values('section').distinct()
Out[5]: [{'section': '1'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, {'section': '2'}, '...(remaining elements truncated)...']

为什么它会返回每个值而不是仅返回不同的值?

供参考,这是我的模型:

class Section(models.Model):
    module = models.ForeignKey(Module, on_delete=models.CASCADE)
    title = models.CharField(max_length=400)
    section = models.CharField(max_length=3)
    topic = models.CharField(max_length=3)
    subtopic = models.CharField(max_length=3)
    subsubtopic = models.CharField(max_length=3)
    language = models.CharField(max_length=2)
    def __str__(self):
        return self.sectionid() + " - " + self.title
    def sectionid(self):
        return self.module.moduleid + ": " + self.justsectionid()
    def justsectionid(self):
        return self.section + "." + self.topic + "." + self.subtopic + \
        self.subsubtopic + "-" + self.language
    class Meta:
        ordering = ['section', 'topic', 'subtopic', 'subsubtopic', 'language']

1 个答案:

答案 0 :(得分:6)

.distinct()与Django ORM存在问题,如果您使用元排序,则会发生此行为。为了使其按预期工作,您需要将排序重置为默认值。您可以通过空白调用.order_by()执行此操作,如下所示:

In [6]: Section.objects.filter(module=15).order_by().values('section').distinct()
Out[6]: [{'section': '1'}, {'section': '2'}, {'section': '3'}]