页面点击按钮实现排序

思路:用ajax实现局部 div 元素更新, 新写一个要更新 div 部分的html页面

models

class Article(models.Model):
    title = models.CharField(max_length=100, verbose_name='文章标题')
    
class Org(models.Model):
    name=models.CharField(max_length=30, verbose_name='公司名')
    
class Author(models.Model):
    username = models.CharField(max_length=30, verbose_name='用户名')
    articles_collected = models.ManyToManyField(to=Article, verbose_name='收藏的文章')
    org = models.ForeignKey(to=Org, on_delete=models.CASCADE, null=True)

一. 修改show-org.html

1.添加排序按钮
 <form id="order_select">
  <div style="float: left; margin-left: 100px;">
    排序:
      <input type="button" name = "article" onclick="orderArticle(this.name)" value="文章数">
      <input type="button" name = "author" onclick="orderAuthor(this.name)" value="作者数">
    
  </div>
  </form>

注意这里的事件点击事件onclick="orderArticle(this.name)",参数 里面获取input标签的name属性

2.添加点击事件
<script type="text/javascript">

function orderArticle(name){
  $.ajax({
      type: "GET",
      url: "/web/org_order/",    
      data: {'data': name},
      success: function (data) {
          $("#content").html(data);
      }
    })
}

function orderAuthor(name){
  $.ajax({
      type: "GET",
      url: "/web/org_order",
      data: {'data': name},
      success: function (data) {
          $("#content").html(data);
      }

    })
}

</script>

二. urls.py中添加

path('org_order/', org_order)

三. views中添加org_order函数

from django.db.models.aggregates import Count

def org_order(request):
  if request.method == 'GET':
    order_key = request.GET.get('data')
    print(order_key, type(order_key))

    if order_key == "author":
      print("author")
      orgs = Org.objects.annotate(num=Count('author__username')).order_by('num')
    
    if order_key == "article":
      print('article')
      orgs = Org.objects.annotate(num=Count('author__articles_collected')).order_by('num')

  for i in range(len(orgs)):
    orgs[i].counts = orgs[i].author_set.all().values('articles_collected').count()

  return render(request, "web/show-org-ajax.html", locals())
  

说明:annotate用来统计字段数量

四. show-org-ajax.html页面


<div id="content">
<div style="padding-left: 25px; ">
  <table class="table"  >
    <thead>
      <tr>
        <th>名称</th>
        <th>作者数量</th>
        <th>文章数</th>
      </tr>
    </thead>
    <tbody>
      {% for row in orgs %}
        <tr>
          <td>{{ row.name }}</td>
         
          <td>{{ row.author_set.all.count }}</td>
  
          <td>{{ row.counts }}</td>
  
        </tr>
      {% endfor %}
    </tbody>
  </table>
  </div>
</div>

show-org-ajax.html里的内容,其实就是原先show-org.html页面中id="content"的div元素,拷贝过来

posted @ 2022-11-21 17:00  坚强的小蚂蚁  阅读(288)  评论(0编辑  收藏  举报