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

Django ORM returning the same values multiple times when using .distinct()

在一组对象上使用 .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']

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

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