Python 在 Django 中与众不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15626175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:34:30  来源:igfitidea点击:

DISTINCT ON in django

pythonmysqldjango

提问by David542

How would I do the following query:

我将如何执行以下查询:

OrderNotes.objects.filter(item=item).distinct('shared_note')

Basically, I need to get all OrderNotesitems, distinct on shared_note. When I try and do this I get:

基本上,我需要获取所有OrderNotes项目,在shared_note. 当我尝试这样做时,我得到:

    raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')

NotImplementedError: DISTINCT ON fields is not supported by this database backend

I am using mysql and cannot change the db here. What would be the workaround in django?

我正在使用 mysql 并且无法在此处更改数据库。Django 中的解决方法是什么?

采纳答案by catherine

OrderNotes.objects.filter(item=item).values_list('shared_note', flat=True).distinct()

回答by David542

This is the best I came up with:

这是我想出的最好的:

>>> items, item_ids = [], []
>>> for item in OrderNotes.objects.filter(shared_note=219):
...     if item.shared_note not in item_ids:
...         items.append(item)
...         item_ids.append(item.shared_note)