Django模型-获取不同值lis

2024-04-19 06:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着得到一个不同外键的列表,我写了这样一个:

my_ids = Entity.objects.values('foreign_key').distinct()

但我得到的只是一个未加密的外键列表。。。我错过了什么?

谢谢!


Tags: keyids列表objectsmy外键entityvalues
3条回答

这是暗示!两种解决方案都不会100%奏效。。。但我把它们结合起来了:)

对于MySQL数据库(afaik),向distinct传递参数不起作用

这个函数只返回一个对象:

Entity.objects.order_by('foreign_key').values('foreign_key').distinct()

但无论如何还是要谢谢:)

或许你应该这样说:

Entity.objects.order_by().values_list('foreign_key', flat=True).distinct()
Entity.objects.values_list('foreign_key', flat=True).distinct().order_by()

明显不适用于

Any fields used in an order_by() call are included in the SQL SELECT columns. This can sometimes lead to unexpected results when used in conjunction with distinct(). If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned.

Similarly, if you use a values() query to restrict the columns selected, the columns used in any order_by() (or default model ordering) will still be involved and may affect uniqueness of the results.

The moral here is that if you are using distinct() be careful about ordering by related models. Similarly, when using distinct() and values() together, be careful when ordering by fields not in the values() call.

https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

相关问题 更多 >