【发布时间】:2014-04-30 19:36:31
【问题描述】:
假设我们有以下模型:
class Item(models.Model):
pass
class Action(models.Model):
item = models.ForeignKey(Item, related_name='actions')
type = models.PositiveSmallIntegerField(default=1)
类型 = 1 或 2
我需要找到 type1 操作最多但 type2 操作不超过 type1 的前 3 个项目。 (count_of_action1 > count_of_action2)
测试:
#item : {type1: action_count, type2: action_count}
1: {1: 5, 2: 2},
2: {1: 4, 2: 2},
3: {1: 3, 2: 2},
4: {1: 3, 2: 1},
5: {1: 6, 2: 7},
应该产生 [1,2,3] 但不是 5。
查询必须非常高效,因为操作和项目的数量非常大。 底层数据库是 MySQL。
有人知道如何使用 Django ORM 实现上述目标吗?
【问题讨论】:
-
我认为你应该使用
queryset object的extra方法。您不妨创建自己的经理来“透明地”处理查询。
标签: python sql database django django-models