正在使用django应用程序,使用几个复杂的查询来返回排名,比率和其他复杂的输出。我从网上跟踪了一些例子,它帮助我找到了最好的方法来放置它并从返回的查询集中检索数据
然而,我想找到一种方法将自定义详细信息注入给定记录,例如在我的情况下,我试图将get_absolute_url()值关联到返回的记录集
下面是一个返回最常用兴趣的示例,此查询将始终返回有限的查询集,是否有方法使用模型的get_absolute_url()值扩展返回的字典?
def most_used_interests(self, limit_by=10):
cursor = connection.cursor()
cursor.execute("""
SELECT
i.name,
i.name_ar,
i.name_en,
ij.interest_id,
SUM (ij.C) item_count
FROM
(
SELECT
C .interest_id,
COUNT (b. ID) C
FROM
bargain_bargain b,
bargain_bargain_bargain_target C
WHERE
b. ID = C .bargain_id
GROUP BY
C .interest_id
UNION
SELECT
x.interest_id,
COUNT (P . ID) C
FROM
promotion_promotion P,
promotion_promotion_promo_target x
WHERE
x.promotion_id = P . ID
GROUP BY
x.interest_id
) ij, list_interest i
WHERE i.id=ij.interest_id
GROUP BY
ij.interest_id,
i.name,
i.name_ar,
i.name_en
ORDER BY
item_count DESC
LIMIT %s
""", [limit_by, ])
desc = cursor.description
if cursor.rowcount:
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
return None
答案 0 :(得分:1)
我找到了一种更简单的方法来处理这种情况,对于遇到类似问题的其他人,我将查询包装为始终返回对象,然后使用objects.raw返回查询
def most_used_interests(self, limit_by=10):
return self.raw("""
SELECT
*
FROM
list_interest l,
(
SELECT
ij.interest_id,
SUM (ij. C) item_count
FROM
(
SELECT
C .interest_id,
COUNT (b. ID) C
FROM
bargain_bargain b,
bargain_bargain_bargain_target C
WHERE
b. ID = C .bargain_id
GROUP BY
C .interest_id
UNION
SELECT
x.interest_id,
COUNT (P . ID) C
FROM
promotion_promotion P,
promotion_promotion_promo_target x
WHERE
x.promotion_id = P . ID
GROUP BY
x.interest_id
) ij
GROUP BY
ij.interest_id
LIMIT %s
) tl
WHERE
l. ID = tl.interest_id
ORDER BY
item_count DESC
""", [limit_by, ]