首页 > 解决方案 > return different queryset with different radio button in template in the same page django

问题描述

I want to render different queryset when user click radio button without submitting the radio button input.

My models are these:

class A(models.Model):
    name = models.CharField(max_length=10)

    def get_a_list(self):
        return self.b_set.filter(name__endswith='lorem')

    def get_b_list(self):
        return self.b_set.filter(name='blah')

class B(models.Model):
    dept = models.ForeignKey(A, on_delete=models.CASCADE)

In template I can do something like this:

<ul>
{% for a in a.objects.all %}
{% for b in a.b_set.all %} <!-- instead of returning all I can do a.get_a_list or b.get_b_list -->
  <li></li>
{% endfor %}
{% endfor %}
</ul>

If I have a group of radio buttons in the same template like this:

<div>
  <input type="radio" id="a-list" value="a-list" name="filter">
  <label for="a-list">a_list</label>
</div>
<div>
  <input type="radio" id="b-list" value="b-list" name="filter">
  <label for="b-list">b_list</label>
</div>
<div>
  <input type="radio" id="all" value="all" name="filter">
  <label for="all">all</label>
</div>

When user select a-list button, I want to call get_a_list, and for b-list button, get_b_list. I want to display the result without changing url.

I managed to get those different list by putting custom method in models class, but I'm lost. And I know I might lose some reputation for this question, for it might be so easy for somebody.

Any suggestion would be so grateful. Thank you in advance.

标签: djangoajax

解决方案


Something like:

template.html:

<div id='a_set'>
  {% for a in a.objects.all %} 
    ...
  {% endfor %}
</div>

<div id='b_set'>
  {% for b in a.b_set.all %}
    ...
  {% endfor %}
</div>

script.js:

function change_sets() {
 if ($('#a-list').is(':checked')) {
    $('#a_set').show();
    $('#b_set').hide();
  }
  else if ($('#b-list').is(':checked')) {
    $('#a_set').hide();
    $('#b_set').show();
  } 
} 

$('#a-list').click(change_sets);
$('#b-list').click(change_sets);

推荐阅读