Django过滤具有值列表的对象

时间:2016-11-11 15:47:32

标签: ajax django

我有一个带有ManyToManyField的字段,并希望使用值列表过滤我的对象。我从下拉列表中获取此值。

我的模板

<form class="" action="." method="get">
  <div class="SearchWithTags">
    <select name="searchcategory" id="TagDropDown">
          {% for k in types_list %}
            <option>{{k.name}}</option>
          {% endfor %}
    </select>
    <div class="PlaceForTags">
      <div id="PlaceForTagsId" class="Tags">

      </div>
      <a href="#"><img src="{% static 'assets/search.png' %}"></a>
    </div>
  </div>
    <input id="SendTagArray" type="submit" class="Search" name="startsearch" value="search">
</form>

我创建了这个值的数组

values = [];

$(function() {

$('#TagDropDown').change(function() {
    values.push($('#TagDropDown option:selected').text());
            $('#PlaceForTagsId').append("<div class='tagex'>" +$('#TagDropDown option:selected').text()+"</div>");

});

    $("#SendTagArray").click(function(){
        console.log(values);
        $.ajax({
         type: 'GET',
         url: '/sitelink/',
         data: {'tags': values},
        });
    });

});

views.py

tags = request.GET.getlist('tags', '')
if searchbutt:
    if tags != '':
        search_filter_kw['tags__name__in'] = tags

但我遇到的问题是它没有向我的视图发送值,而且标签变量为空。

1 个答案:

答案 0 :(得分:1)

如何使用request.GET.getlist('tags[]', '')

搜索前的结果

before

按ajax搜索后的结果

after

以下示例是如何实现它。

实施例

<强> 1。 yourapp/models.py

from django.db import models

class Foo(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name


class Ref(models.Model):
    foo = models.ManyToManyField(Foo, related_name='ref_foo')
    other = models.CharField(max_length=200)

    def __str__(self):
        return self.other

<强> 2。 yourapp/views.py

from django.shortcuts import render
from foo.models import (Foo, Ref)

def fooview(request):
    foos = Foo.objects.all()
    refs = Ref.objects.all()
    return render(
      request, 'foo.html', 
      {'types_list': foos, 'refs': refs}
    )

def search(request):
    if request.is_ajax():
        tags = request.GET.getlist('tags[]', '')
        #print(tags)
        if tags != '':
            results = Ref.objects.filter(foo__name__in=tags).distinct()
            return render(
              request, 'search.html', 
              {'results': results, 'tags': tags}
            )
    return render(request, 'search.html', {})

第3。 yourapp/urls.py

from django.conf.urls import url
from yourapp.views import (fooview, search)

urlpatterns = [
    url(r'^$', fooview, name='foo'),
    url(r'^search/$', search, name='search')
]

第3。 templates/foo.html

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body>
<div class="original-data">
 Original Data:<br />
 {% for ref in refs %}
   <li>{{ ref }} - {% for foo in ref.foo.all %}{{ foo }}, {% endfor %}</li>
 {% endfor %}
</div>
<hr />

<div class="main-search">
  <div class="SearchWithTags">
    <select name="tags" id="TagDropDown">
      <option>Choice categories...</option>
      {% for k in types_list %}
        <option value="{{ k.name }}">{{ k.name }}</option>
      {% endfor %}
    </select>
    <div class="PlaceForTags">
      <div id="PlaceForTagsId" class="Tags">
      </div>
    </div>
  </div>
  <button id="SendTagArray" class="search">Search...</button>
</div><!-- end /.main-search -->

<div class="main-results">
</div>

<script>
  values = [];
  $(function() {
    $('#TagDropDown').change(function() {
        var val = $('#TagDropDown option:selected').text();
      // check if has duplicate values
      if (values.includes(val) == false){
        values.push(val);
        $('#PlaceForTagsId').append("<div class='tagex'>" +$('#TagDropDown option:selected').text()+"</div>");
      }
    });
    $("#SendTagArray").click(function(){
      console.log(values);
      $.ajax({
        type: 'GET',
        url: '{% url "search" %}',
        data: {
          'csrfmiddlewaretoken': '{{ csrf_token }}', 
          'tags': values
        },
        success: function(data) {
           $('.main-results').html(data);
        },
        error: function(data) {
           console.log(data);
        }
      });
    });
  });
</script>
</body>
</html>

<强> 4。 templates/search.html

<div class="results">
  Result of {{ tags }}:
  <hr />

  {% for result in results %}
    <li>{{ result }}</li>
  {% endfor %}
</div>