Django:使用相同的对象如何在django模板中显示2个不同的结果? [英] Django: Using same object how to show 2 different results in django template?
问题描述
使用相同的对象如何使用django模板显示2个不同的结果?
Using the same object how to SHOW 2 different results using django template ?
在一个页面中有两个div,它应该使用相同的对象显示不同的信息。
In one page there are two div's, it should show different information using the same object.
INPUT
对象数据遵循 / p>
object data has follows
[
{
"Google": [
{
"Rating": 1,
"Website": {
"id": "1",
"Name": "googleplus"
}
},
{
"Rating": 2,
"Website": {
"id": "1",
"Name": "googleplus"
}
},
{
"Rating": 1,
"Website": {
"id": "2",
"Name": "googlemap"
}
}
]
},
{
"Facebook": [
{
"Rating": 1,
"Website": {
"id": "1",
"Name": "facebookplus"
}
},
{
"Rating": 2,
"Website": {
"id": "1",
"Name": "facebookplus"
}
},
{
"Rating": 1,
"Website": {
"id": "2",
"Name": "facebookmap"
}
}
]
}
]
DESIRED OUTPUT
DIV 1(网站名称应为唯一值)
DIV 1 (website names should be unique values)
DIV 2(应显示所有网站名称)
DIV 2 (should display all website names)
主div开始
循环1
Google ------ DIV 1 (googleplus, googlemap) ------ DIV 2 (googleplus, googleplus, googlemap)
循环2
Facebook ------ DIV 1 (facebookplus, facebookmap) ------ DIV 2 (facebookplus, facebookplus, facebookmap)
主div end
推荐答案
模板仅用于显示给定的数据。如果你想操纵数据,你必须这样做。这将会更容易一些,因为您可以使用普通的Python语法。
Template is used only to display given data. If you want to manipulate data, you have to do this in view. It'll be a lot easier, as you can use normal python syntax.
您可以使用以下内容:
all_data = <object_name>.objects.all()
unique_data = list(set(all_data))
更新
如果要在前端执行此操作,我会推荐使用 Lodash库。
If you want to do this on frontend, I would recommend using Lodash library.
但是你可以当然可以使用简单的JavaScript:
But you can of course do it in plain JavaScript:
var all_data = ...;
var unique_data = [];
for (i = 0; i < all_data.length; i++) {
if (unique_data.indexOf(all_data[i]) < 0) unique_data.push(all_data[i]);
}
这篇关于Django:使用相同的对象如何在django模板中显示2个不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!