如何在django上按时间过滤数据?

时间:2016-12-27 07:14:20

标签: python django django-templates

我对django中的过滤数据有一些问题,我希望过滤器选择选项 pagi 将显示数据时间从00:00到10:00 ,如果选择选项 siang 将显示数据从10:01到18:00 ,如果选择选项 malam ,它将从18:00显示数据到23:59 , 我有这样的代码模板/ index.html:

<!DOCTYPE html>
<head>
  <html>
  <meta charset="utf-8">
  <title>This Is Latihan</title>
</head>
<body>
<div id="form">
  <form action="{% url insert %}" method="POST">{% csrf_token %}
      Nama Maskapai   : <input type="text" name="airline" id="airline" value="{{ airline }}"></input> </br>
      Waktu Berangkat : <input type="text" name="time" id="time" value="{{ time }}"></input> </br>
      <input type="submit" name="save" value="save">
  </form>
</div>

<table id="table" border="1">
  <tr>
    <th align="center" width=30px>No.</th>
    <th align="center" width=150px>Maskapai</th>
    <th align="center" width=70px>Waktu</th>
    <th align="center" width=230px colspan="4">Action</th>
</tr>
    {% for i in maskapai %}
  <tr>
      <td align="center" width=30px>{{ forloop.counter }}</td>
      <td width=150px>{{ i.airline }}</td>
      <td width=70px> {{ i.time }}</td>
      <form action="{% url action %}" method="POST">{% csrf_token %}
      <td width=230px colspan="4">
        <input type="hidden" name="index" value= "{{ forloop.counter0 }}" />
        <input type="hidden" name="time" value= "{{ i.time }}" />
        <input type="submit" name="delete" value="delete">
        <input type="submit" name="up" value="up">
        <input type="submit" name="down" value="down">
      </td>
      </form>
  </tr>
  {% endfor %}
</table>

  <form action="{% url filter %}" method="POST">{% csrf_token %}
    <select name="maskap">
      <option value="all">-Pilih Maskapai-</option>
      {% for pil in pilihan %}
      <option value="{{ pil }}"> {{ pil }} </option>
      {% endfor %}
    </select>

    <select name="waktu">
      <option value="allwak"> -Pilih Waktu- </option>
      <option value="pagi">pagi</option>
      <option value="siang">siang</option>
      <option value="malam">malam</option>
    </select>
    <input type="submit" name="name" value="FILTER">
</form>
<br>
</body>

</html>

这是我的观点代码:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
import time

maskapai_glob = []
pilihan_glob = []
def index(request):
    return render_to_response('index.html', locals(), context_instance=RequestContext(request))

def insert(request):
    if request.POST:
        airline = str(request.POST.get('airline'))
        times = str(request.POST.get('time'))
        try:
            # Diisi ReGex Jam
            tim = time.strptime(times,'%H:%M')
            # time = "%s:%s" % (tim.hour, tim.minute)
            insert_data = {'airline':airline, 'time':times}
        except Exception, err:
            print err
            return HttpResponse("""<h2>Jam Salah</h2><button onClick='window.history.back()'>back</button>""")


        maskapai = [i for i in maskapai_glob]
        pilihan = [i for i in pilihan_glob]

        maskapai.append(insert_data)
        maskapai_glob.append(insert_data)

        if len(pilihan) == 0:
            pilihan.append(airline)
            pilihan_glob.append(airline)
        elif len(pilihan) >= 1:
            if airline in pilihan:
                pass
            else:
                pilihan.append(airline)
                pilihan_glob.append(airline)

        return render_to_response('index.html', locals(), context_instance=RequestContext(request))

def action(request):
    if request.POST:
        if request.POST.get('delete'):
            val_maskapai = []
            index = int(request.POST.get('index'))
            airline = str(request.POST.get('airline'))
            del maskapai_glob[index]

            maskapai = [i for i in maskapai_glob]
            pilihan = [i for i in pilihan_glob]

            for i in range(len(maskapai_glob)):
                val_maskapai.append(maskapai[i]['airline'])

            for i in pilihan_glob:
                if i in val_maskapai:
                    pass
                else:
                    pilihan_glob.remove(i)
                    pilihan.remove(i)

            return render_to_response('index.html', locals(), context_instance=RequestContext(request))

        elif request.POST.get('up'):
            index_up = int(request.POST.get('index'))
            index_down = index_up - 1
            data_one = maskapai_glob[index_down]
            data_two = maskapai_glob[index_up]
            if index_up == 0:
                pass
            else:
                maskapai_glob[index_down] = data_two
                maskapai_glob[index_up] = data_one
            maskapai = [i for i in maskapai_glob]
            return render_to_response('index.html', locals(), context_instance=RequestContext(request))

        elif request.POST.get('down'):
            index_down = int(request.POST.get('index')) # data can be down
            last_index = len(maskapai_glob) - 1
            if index_down == last_index:
                pass
            else:
                index_up = index_down + 1 # data can be up
                data_one = maskapai_glob[index_down] # data down
                data_two = maskapai_glob[index_up] # data up
                maskapai_glob[index_down] = data_two
                maskapai_glob[index_up] = data_one
            maskapai = [i for i in maskapai_glob]
            return render_to_response('index.html', locals(), context_instance=RequestContext(request))

def filter(request):
    if request.POST:
        getmask = request.POST.get('maskap')
        getwaktu = request.POST.get('waktu')

        if getmask:
            if getmask == 'all':
                maskapai = [i for i in maskapai_glob]
                pilihan = [i for i in pilihan_glob]
                #Mulai dari sini
                if getwaktu == "pagi":
                    maskapai = [] #maskapai
                    pilihan = [i for i in pilihan_glob] #pilihan option

                    data_pilihan = request.POST.getlist(str('waktu')) #mengambil data dari select (maskap)
                    list_pilihan = [str(i) for i in data_pilihan] #list pilihan dari data maskap

                    for i in range(len(maskapai_glob)):
                        if 'pagi' in list_pilihan:
                            #maskapai.append(maskapai_glob[i])
                            return HttpResponse("test");
                    #return HttpResponse("test");
                    return render_to_response('index.html', locals(), context_instance=RequestContext(request))
                #Sampai sini


                return render_to_response('index.html', locals(), context_instance=RequestContext(request))

            else:
                maskapai = [] #maskapai
                pilihan = [i for i in pilihan_glob] #pilihan option
                data_pilihan = request.POST.getlist(str('maskap')) #mengambil data dari select (maskap)

                list_pilihan = [str(i) for i in data_pilihan] #list pilihan dari data maskap

                for i in range(len(maskapai_glob)):
                    if maskapai_glob[i]['airline'] in list_pilihan:
                        maskapai.append(maskapai_glob[i])

                return render_to_response('index.html', locals(), context_instance=RequestContext(request))

方法过滤器是过滤功能。

1 个答案:

答案 0 :(得分:1)

您目前正在使用全局变量而不是Django的ORM - 这是一种不好的做法!按照tutorial学习如何使用Django创建数据库模型。 假设您正在使用Django的ORM,请尝试:

FILTERS = {
 'pagi': (None, "10:00"),
 'siang': ("10:00", "18:00"),
 'malam': ("18:00", None),
}

a, b = FILTERS[request.POST['waktu']]

然后查询您的数据库,假设您的模型date中有DateField timeTimeField MyModel

qs = MyModel.objects.filter(date=x)
if a:
    qs = qs.fiter(time__gte=a)
if b:
    qs = qs.fiter(time__lt=b)