django - 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.
解决方案
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);
推荐阅读
- java - 在java中从两个单独的季度添加数组总计
- java - 构建和运行底部导航活动时出现空指针异常
- assembly - ARM AS 汇编程序 read() 在 printf() 之前运行,但 printf() 是前面的语句
- python-3.x - SSL: CERTIFICATE_VERIFY_FAILED” 错误 --> EVEN 安装后
- fortran - 如何将 Fortran MAX(0D0, X) 转换为另一种语言
- ios - Swift - 带有嵌入式 UIStackView 的 UIScrollView 的无限滚动
- typescript - 元组镇的打字稿麻烦:保留参数类型
- c# - 在屏幕上滑动以在游戏中滑动
- python - 在python中使用for循环或嵌套循环创建多个附加数组的数据框
- reactjs - 我该如何解决这个 try catch 问题