基于许多领域中的选择的Django链过滤结果

时间:2018-07-14 09:35:42

标签: django django-forms manytomanyfield

我有以下型号:

this.http.get(window["DATA_URL"]).subscribe(...)

假设我在表单或管理字段中添加了多个国家/地区。有没有一种方法可以根据我在“国家/地区”字段中选择的内容从“状态”字段中过滤结果?

例如:

class Country(models.Model):
    name = models.CharField(max_length=50)

class State(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name =  models.CharField(max_length=50, null=False, blank=False)

class Species(models.Model):
    name = models.CharField(max_length=50, null=False, blank=False)
    country =models.ManyToManyField(Country)
    state =models.ManyToManyField(State)

如果我选择Countries: States USA: CA, VA, NV, OR Mexico: PUB, JAL, SIN Canada: NU, ON, QC USA,则表单上的状态字段将产生:

Canada

与我类似,我能找到的最接近的东西是django-smart-select,但不适用于我的情况。

1 个答案:

答案 0 :(得分:0)

我将使用Ajax + JS来实现这一目标。我会按照以下方式进行操作(我尚未测试此代码):

HTML:

<select name="country">
  <option value="">Choose a country</option>
  <option value="USA">USA</option>
  <option value="Mexico">Mexico</option>
  <option value="Canada">Canada</option>
</select>

<select name="state" disabled>
  <option value="">Choose a state</option>
</select>

JS:

$('select[name="country"]').on('change', function() {
  var country = $(this).val();
  var states = [];
  $('select[name="state"] option:gt(0)').remove(); // cleaning: removes all options except the first

  if (!(country)) {
    $('select[name="state"]').prop("disabled", true);
  } else {
    $.ajax({
      url: "{% url 'get_states' %}",
      dataType: "json",
      data: {
        country: country
      },
      success: function(data) {
        data = JSON.parse(data);
        for (var key in data) {
          $('select[name="state"]').append(
            $('<option>', {
              value: key,
              text: data[key]
            })
          );
        }
      }
    });
    $('select[name="state"]').prop("disabled", false);
  }
});

在urls.py中:

url(r'^getstates$', 'myapp.views.get_states', name='get_states'),

在views.py中:

from django.shortcuts import HttpResponse
import json
from myapp.models import Country, State


def get_states(request):
    if request.is_ajax():
        country = request.GET.get('country', '')
        states = State.objects.filter(country__name=country)
        state_dict = {}
        for state in states:
            state_dict[state.pk] = state.name
        return HttpResponse(json.dumps(state_dict))

希望这会有所帮助!