Job Search Engine


810 浏览 5 years, 1 month

2.19 统计

版权声明: 转载请注明出处 http://www.codingsoho.com/

统计

安装chartjs

pip install django-chartjs==1.2

视图

from chartjs.views.lines import (JSONView, BaseLineChartView)

views.py

class LastestChartJSONView(LineChartColorMixin, BaseLineChartView):
    def get_labels(self):
        """Return labels for the x-axis."""
        return [(datetime.datetime.now() - datetime.timedelta(weeks=i)).date() for i in range(0,5)]
    def get_providers(self):
        """Return names of datasets."""
        providers =  [ "Job Numbers", ]
        return providers
    def get_data(self):
        data = [
            [
                # self.get_queryset().filter(created__startswith=label).count()
                self.get_queryset().filter(created__lte=label).count()
                for label in self.get_labels()
            ]
            for provider in self.get_providers()
        ]
        return data

模板

job_entry_list.html

    <canvas id="pieChart" width="500" height="200"></canvas>
    <script>   
      $(function () {
        $.get('{% url "jobentry_stat_api" %}', function(data) {
          var ctx = $("#pieChart").get(0).getContext("2d");
          var myChart = new Chart(ctx, {
              type: 'bar', 
              data: data,
              options: {
                  scales: {
                      yAxes: [{ // [https://www.chartjs.org/docs/latest/axes/cartesian/linear.html](https://www.chartjs.org/docs/latest/axes/cartesian/linear.html)
                          scaleLabel: {
                              display: true,
                              labelString: 'Number of Jobs'
                          },
                          ticks: {
                              beginAtZero:true,
                              min: 0,
                              // max:100,
                              stepSize:20,
                              suggestedMin: 0,                              
                          }
                      }],
                      xAxes: [{
                          gridLines: {
                              offsetGridLines: true,  
                          },
                          barPercentage: 0.8,
                      }]                    
                  }                
              }            
          });          
        });     
      });
    </script>

如何在JSON视图里根据query过滤object_list

URL里添加query

$.get('{% url "jobentry_stat_api" %}?{{request.GET|my_urlencode}}', function(data)

这个地方用templatetag对request.GET进行了编码,实现如下

@register.filter(name='my_urlencode')
def my_urlencode(data):
    from urllib import urlencode, quote
    import chardet
    d = dict(data)
    for key,value in d.items():
        value = value[0]
        if isinstance(value, unicode):
            value = value.encode('utf-8')
            if value:
                print("(1)", value, type(value),chardet.detect(value).get('encoding'))
        if value:
            d[key] = quote(value)
            print("(2)", d[key], type(d[key]), chardet.detect(d[key]).get('encoding'))
        else:
            d[key] = ''
    return urlencode(d)

视图中添加基类ListView,并获取queryset

class LastestChartJSONView(LineChartColorMixin, BaseLineChartView, ListView):
    model = JobEntry
    filter_class = JobEntryFilter
    def get_queryset(self, *args, **kwargs):
        from urllib import unquote
        import chardet
        qs = super(LastestChartJSONView, self).get_queryset()
        query = self.request.GET.copy()
        for key,value in query.items():
            if value:                                       # <type 'unicode'> %E8%8A%AF%E7%89%87
                print "<0>", type(value), value
                value = str(value)                          # {'confidence': 1.0, 'language': '', 'encoding': 'ascii'} %E8%8A%AF%E7%89%87 <type 'str'>
                print "<1>", chardet.detect(value), value, type(value)
                value = unquote(value)                      # {'confidence': 0.7525, 'language': '', 'encoding': 'utf-8'} 鑺墖 <type 'str'>
                print "<2> - unquote", chardet.detect(value), value, type(value)
                value = value.decode('utf-8')
                print "<3> - decode", value, type(value)
                query[key] = value        
        qs = self.filter_class(query, queryset=qs).qs
        return qs

如果title里包含字符“芯片”,在myform里

如果只是普通的英文字符串,可以直接用urlencode编码,但是中文字符串会报错

'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

所以需要先将它转为字符串,然后编码,分为2步

(1) 如果是unicode,通过encode('utf-8')将它转化为utf-8字符串,显 示结果

'(1)', '\xe8\x8a\xaf\xe7\x89\x87', <type 'str'>, 'utf-8'

(2) 通过quote函数编码,结果

(2)', '%E8%8A%AF%E7%89%87', <type 'str'>, 'ascii'

在view函数里,处理如下

(0) request.GET得到的是unicode,跟myform的str值是一样的

<0> <type 'unicode'> %E8%8A%AF%E7%89%87

(1) 先通过str将它转为字符串

<1> {'confidence': 1.0, 'language': '', 'encoding': 'ascii'} %E8%8A%AF%E7%89%87 <type 'str'>

(2) 通过unquote解码,得到下面输出

<2> - unquote {'confidence': 0.7525, 'language': '', 'encoding': 'utf-8'} 鑺墖 <type 'str'>

(3) 通过decode('utf-8')转为unicode

<3> - decode 芯片 <type 'unicode'>

整个转换的过程解析如下

>>> value_unicode = u'芯片'
>>> type(value_unicode), value_unicode
(<type 'unicode'>, u'\u82af\u7247')

>>> value_utf8 = value_unicode.encode('utf-8')
>>> type(value_utf8), value_utf8, chardet.detect(value_utf8)
(<type 'str'>, '\xe8\x8a\xaf\xe7\x89\x87', {'confidence': 0.7525, 'language': '', 'encoding': 'utf-8'})

>>> value_utf8_quote = quote(value_utf8)
>>> type(value_utf8_quote), value_utf8_quote, chardet.detect(value_utf8_quote)
(<type 'str'>, '%E8%8A%AF%E7%89%87', {'confidence': 1.0, 'language': '', 'encoding': 'ascii'})

# 实际操作中,view没有直接得到这个对应的quote后的string,得到的是unicode,需要通过str强转

>>> value_utf8_quote_unquote = unquote(value_utf8_quote)
>>> type(value_utf8_quote_unquote), value_utf8_quote_unquote, chardet.detect(value_utf8_quote_unquote)
(<type 'str'>, '\xe8\x8a\xaf\xe7\x89\x87', {'confidence': 0.7525, 'language': '', 'encoding': 'utf-8'})

>>> value_utf8_quote_unquote_decode = value_utf8_quote_unquote.decode('utf-8')
>>> type(value_utf8_quote_unquote_decode), value_utf8_quote_unquote_decode
(<type 'unicode'>, u'\u82af\u7247')

<type 'unicode'> %E8%8A%AF%E7%89%87