gpt4 book ai didi

mysql - 简化我的 Django 查询逻辑

转载 作者:行者123 更新时间:2023-11-29 14:42:36 25 4
gpt4 key购买 nike

我有一个看起来像这样的表格。

+----+--------+---------+-----------+------------------------+
| id | parent | type | libTypeId | name |
+----+--------+---------+-----------+------------------------+
| 2 | 1 | project | 2 | 1p6m4x0y1z_1.2-1.8_hvt |
| 5 | 1 | project | 6 | 1p6m4x0y1z_1.2-1.8_hvt |
| 8 | 1 | project | 16 | 1p6m4x0y1z_1.2-1.8_hvt |
| 11 | 1 | project | 21 | 1p6m4x0y1z_1.2-1.8_hvt |
| 3 | 1 | project | 2 | 1p6m4x0y1z_1.2-1.8_lvt |
| 6 | 1 | project | 6 | 1p6m4x0y1z_1.2-1.8_lvt |
| 9 | 1 | project | 16 | 1p6m4x0y1z_1.2-1.8_lvt |
| 12 | 1 | project | 21 | 1p6m4x0y1z_1.2-1.8_lvt |
| 1 | 1 | project | 2 | 1p6m4x0y1z_1.2-1.8_svt |
| 4 | 1 | project | 6 | 1p6m4x0y1z_1.2-1.8_svt |
| 7 | 1 | project | 16 | 1p6m4x0y1z_1.2-1.8_svt |
| 10 | 1 | project | 21 | 1p6m4x0y1z_1.2-1.8_svt |
| 13 | 2 | project | 2 | 065nm_GPIO |
| 17 | 2 | project | 4 | 065nm_GPIO |
| 14 | 2 | project | 6 | 065nm_GPIO |
| 18 | 2 | project | 12 | 065nm_GPIO |
| 15 | 2 | project | 16 | 065nm_GPIO |
| 16 | 2 | project | 21 | 065nm_GPIO |
| 19 | 2 | project | 2 | 065nm_Specialized |
+----+--------+---------+-----------+------------------------+

我正在寻找一个查询,该查询会产生一个列表,其中我们获取 id = 1 的所有项目,该项目仅按名称、libtypeid 和第一个 libtypeid 排序。

换句话说,我应该得到这样的结果:

+----+--------+---------+-----------+------------------------+
| id | parent | type | libTypeId | name |
+----+--------+---------+-----------+------------------------+
| 2 | 1 | project | 2 | 1p6m4x0y1z_1.2-1.8_hvt |
| 3 | 1 | project | 2 | 1p6m4x0y1z_1.2-1.8_lvt |
| 1 | 1 | project | 2 | 1p6m4x0y1z_1.2-1.8_svt |
+----+--------+---------+-----------+------------------------+

现在我可以走到这一步了,但是我怎样才能只得到第一个?

Variant.objects.filter(parent=self.id).order_by('name', 'libtype_id')

然后我进一步这样做..

full = Variant.objects.filter(parent=self.id).order_by('name', 'libtype_id')
names, out = [], []
for v in full:
if v.name not in names:
out.append(v)
names.append(v.name)
return out

如果有人能稍微清理一下,我将不胜感激..

最佳答案

如果我正确理解了这个问题,您需要对您的集合进行“分组”并返回每组的第一行。您需要查看聚合:https://docs.djangoproject.com/en/dev/topics/db/aggregation/

类似的东西

Variant.objects
.values('name', 'libtype_id')
.annotate(min_libtype_id=Min('libtype_id'))
.filter(parent=self.id)
未经测试

关于mysql - 简化我的 Django 查询逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com