【问题标题】:Django ORM returning the same values multiple times when using .distinct()使用 .distinct() 时,Django ORM 多次返回相同的值
【发布时间】:2016-08-22 06:10:53
【问题描述】:

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

【问题讨论】:

    标签: python django django-orm


    【解决方案1】:

    .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'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 2019-02-28
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多