It seems all the D3 example graphs take an external .csv or .tsv file as input data. Is there any way to modify the code to take data from a variable in Django. Suppose {{ data }} is in JSON format, how do you implement this in a graph such as http://bl.ocks.org/3885304 or http://bl.ocks.org/3887051 ? I'm trying to avoid always writing a .csv file.
似乎所有D3示例图都将外部.csv或.tsv文件作为输入数据。有没有办法修改代码从Django中的变量中获取数据。假设{{data}}采用JSON格式,如何在http://bl.ocks.org/3885304或http://bl.ocks.org/3887051等图表中实现?我试图避免总是写一个.csv文件。
2 个解决方案
#1
6
You can always make a view which will serve dynamic csv file which will be consumed by D3. This way will also allow users to download the data in case they need the raw data instead of a graph.
您始终可以创建一个视图,该视图将提供D3将使用的动态csv文件。这种方式还允许用户在需要原始数据而不是图表时下载数据。
def foo(request, ...):
model = get_object_or_404(Foo, ...)
data = model.get_data() # should return csv formatted string
return HttpResponse(data, content_type='text/csv')
#2
5
Instead of loading data asynchronously (ajax-style), you can use correctly formatted JSON in a string passed to your template tag variable and |safe
d.
您可以在传递给模板标记变量和| safed的字符串中使用格式正确的JSON,而不是异步加载数据(ajax样式)。
Check out the working example http://bl.ocks.org/4040034 which is based on http://bl.ocks.org/3885304
查看基于http://bl.ocks.org/3885304的工作示例http://bl.ocks.org/4040034
You should also check out the related questions on SO, there are tons on the subject.
您还应该查看SO上的相关问题,这个主题有很多。
#1
6
You can always make a view which will serve dynamic csv file which will be consumed by D3. This way will also allow users to download the data in case they need the raw data instead of a graph.
您始终可以创建一个视图,该视图将提供D3将使用的动态csv文件。这种方式还允许用户在需要原始数据而不是图表时下载数据。
def foo(request, ...):
model = get_object_or_404(Foo, ...)
data = model.get_data() # should return csv formatted string
return HttpResponse(data, content_type='text/csv')
#2
5
Instead of loading data asynchronously (ajax-style), you can use correctly formatted JSON in a string passed to your template tag variable and |safe
d.
您可以在传递给模板标记变量和| safed的字符串中使用格式正确的JSON,而不是异步加载数据(ajax样式)。
Check out the working example http://bl.ocks.org/4040034 which is based on http://bl.ocks.org/3885304
查看基于http://bl.ocks.org/3885304的工作示例http://bl.ocks.org/4040034
You should also check out the related questions on SO, there are tons on the subject.
您还应该查看SO上的相关问题,这个主题有很多。