【问题标题】:How return json in django for bootstrap table如何在 django 中为引导表返回 json
【发布时间】:2015-08-13 10:47:14
【问题描述】:

如何从查询集返回 json - A.objects.all() 到引导表 (http://wenzhixin.net.cn/p/bootstrap-table/docs/examples.html):

<table data-toggle="table" data-url="data" data-cache="false" data-height="299">
    <thead>
        <tr>
            <th data-field="id">Item ID</th>
            <th data-field="name">Name</th>
        </tr>
    </thead>
</table>

在视图中:

data = serializers.serialize("json", A.objects.all())
return render(request, 'a.html', {'data': data})

【问题讨论】:

  • 为什么要在这里返回一个json?您可以直接向您发送数据而无需序列化它并使用模板标签将它们显示在您的页面中

标签: json django bootstrap-table


【解决方案1】:

有两种模式:服务器或客户端

对于服务器模式:

在 utils.py 中:

from django.core.serializers import serialize
import json
def serialize_bootstraptable(queryset):
    json_data = serialize('json', queryset)
    json_final = {"total": queryset.count(), "rows": []}
    data = json.loads(json_data)
    for item in data:
        del item["model"]
        item["fields"].update({"id": item["pk"]})
        item = item["fields"]
        json_final['rows'].append(item)
    return json_final

在views.py中:

from django.http import JsonResponse
json_send = serialize_bootstraptable(Model.objects.all())
return JsonResponse(json_send, safe=False)

【讨论】:

    【解决方案2】:

    您可以使用 Django JsonResponse。 请参阅文档here

    你会这样做:

    def my_json_view(request):
        context = {'foo': bar}
        return JsonResponse(context)
    

    另请参阅此 SO 问题here

    希望这会有所帮助! :)

    【讨论】:

      【解决方案3】:

      解决方案:

      在视图中:

      def test(request):
          data = A.objects.all().values()
          return render(request, 'test.html', {'data': data})
      

      在模板中:

      <script type="text/javascript">
          $(document).ready(function(){
              $('#table').bootstrapTable({
                 data:{{data|safe}}
              });    
          });
      </script>
      
      <table id="table">
          <thead>
              <tr>
                  <th data-field="id">Item ID</th>
                  <th data-field="name">Name</th>
              </tr>
          </thead>
      </table>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-16
        • 2021-08-18
        • 2014-11-22
        • 2010-11-02
        • 1970-01-01
        • 2017-10-09
        • 2013-02-12
        • 2020-03-31
        相关资源
        最近更新 更多