我正在尝试使用 jchart 模块在Django中创建一个图表,并且能够使用变量 hosp 从数据库中选择要从数据库中检索的行我的 views.py 到 HomeTotalStudies()(下方)
views.py
from charts.chartsclass import HomeTotalStudies
def home(request):
hosp = request.user.userprofile.hospital
chart = HomeTotalStudies()
return render .....
这是 /charts/chartsclass.py
from jchart import Chart
from jchart.config import (DataSet, Axes, rgba, ScaleLabel, Tick, Tooltips,
Legend, LegendLabel, Title, Hover, InteractionModes,
ElementLine, ElementPoint, ElementRectangle)
class HomeTotalStudies(Chart):
chart_type = 'pie'
responsive = False
def get_labels(self,**kwargs):
return ["CT","MG","RF","DX"]
def get_datasets(self,**kwargs):
modality = ['CT','MG','RF','DX']
count = []
if hosp=='somestring' #this is the variable i want to get from the views.py
studies = GeneralStudyModel.objects.all()
else:
studies = GeneralStudyModel.objects.filter(equipmentattributes__institution_name__exact=hosp)
for mod in modality:
cc = studies.objects.filter(modality_type__exact=mod).count()
count.append(cc)
data = [count[i] for i in range(len(count))]
colors = [
rgba(255,99,132,1),
rgba(54,162,235,1),
rgba(255,159,64,1),
rgba(255,206,86,1)
]
return [DataSet(label="My DataSet",
data=data,
borderWidth=1,
backgroundColor=colors,
borderColor=colors)]
所以,我的问题是,如何将这个变量 hosp 从视图传递给图表类,以便我可以查询db表GeneralStudyModel并且只检索所需的行?
任何人都有任何建议/想法/解决方案吗?
由于
答案 0 :(得分:0)
是的。
你有两个可能性:
class-based-view
来制作现代应用程序,并在您的班级中覆盖方法get_context_data()
class GeneralStudyResultsView(generic.TemplateView):
template_name='general_study_results.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(GeneralStudyResultsView, self).get_context_data(**kwargs)
# Create a variable you fill
context['my_big_sql'] = GeneralStudyModel.objects.all()
return context
从那里开始,在您的模板文件中(这是您的模板文件,而不是JavaScript文件)general_study_results.html
添加如下内容:
<script>
var myData =
{% for row in my_big_sql %}
{{ row.column }}{% if not forloop.last %},{% endif %}
{% endfor %};
</script>
然后,由于charts.js
答案 1 :(得分:0)
只需向图表类添加一个合适的初始化器,如下所示:
class HomeTotalStudies(Chart):
def __init__(self, hosp, *args, **kwargs):
self.hosp = hosp
super().__init__(*args, **kwargs)
def get_datasets(self,**kwargs):
modality = ['CT','MG','RF','DX']
count = []
if self.hosp=='somestring' #this is the variable i want to get from the views.py
studies = GeneralStudyModel.objects.all()
else:
studies = GeneralStudyModel.objects.filter(equipmentattributes__institution_name__exact=self.hosp)
...
然后在您看来:
from charts.chartsclass import HomeTotalStudies
def home(request):
hosp = request.user.userprofile.hospital
chart = HomeTotalStudies(hosp='whatever')
return render .....