[英]How to group rows containing similar element from a table using MYSQL/ Python / Django?
我的HMTL頁面中有一個正在渲染的表。 數據來自MYSQL查詢,並使用循環呈現。 假設我有這張桌子:
我能夠按模型獲取這些數據->視圖-> html
意見:
def context(request):
context = {
"contents": Something.objects.get_contents()
}
return render(request, 'contents.html', context)
請注意,唯一重復的優先級是“新聞”類型。 我希望有4條新聞出現,他們可以分享相似的優先事項。 任何其他體裁都應該有自己的優先級。 如何編寫查詢並將其呈現到html頁面以產生如下輸出:
我感謝所有的幫助! 謝謝。
我認為使用SQL查詢沒有簡單的方法,請嘗試使用Python進行收集。 進行defaultdict,使您可以將內容字段收集到列表中:
from collections import defaultdict
contents_dict = defaultdict(list)
for priority, type, content in Something.objects.get_contents():
contents_dict[(priority, type)].append(content)
然后重建為元組列表
table = [key + (','.join(s),) for key, s in contents_dict.items()]
那么您的視圖如下所示:
def context(request):
context = {
"contents": table
}
return render(request, 'contents.html', context)
您可以使用GROUP BY和GROUP_CONCAT,如下所示:
SELECT priority, type, GROUP_CONCAT(content SEPARATOR ', ') FROM table GROUP BY priority, type;
參考: https : //dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.