最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django實現(xiàn)列表頁商品數(shù)據(jù)返回教程

 更新時間:2020年04月03日 11:05:23   作者:讓我在雪地上撒點野  
這篇文章主要介紹了Django實現(xiàn)列表頁商品數(shù)據(jù)返回教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

采用的是cbv方式,cbv就是在url中一個路徑對應一個類

rom django.views.generic import View
from goods.models import Goods
 
 
class GoodsListView(View):
"""
   通過django的view實現(xiàn)商品列表頁
   :param request:
   :return:
   """
  def get(self,request):
  #重寫View中的get方法
   goods_list = Goods.objects.all()[:10]
  #返回前所有商品的前10條數(shù)據(jù)
   json_list = []
   for goods in goods_list:
     json_item = {}
     json_item["name"] = goods.name
     json_item["market_price"] = goods.market_price
     json_item["sold_num"] = goods.sold_num
 
     json_list.append(json_item)
 
   from django.http import HttpResponse
   import json
 
   content = json.dumps(json_list)
   #將JSON格式轉成python字符串
   return HttpResponse(content,"application/json")

在urls.py文件中配置函數(shù)對應的路由

from goods.views_base import GoodsListView
 
urlpatterns = [
"""
  #商品列表的路由
  url(r'^goods/$',GoodsListView.as_view(),name="goods_list")
"""
]

接下來我們就可以通過url看到返回的數(shù)據(jù)信息了

補充知識:django通過ajax請求接口返回多條數(shù)據(jù),并動態(tài)生成表格,請求表單后將表格數(shù)據(jù)并入庫

一、最近在做接口相關的開發(fā),需求是這樣的,通過一個接口所需要傳遞的參數(shù),調用接口后,處理接口響應的參數(shù),返回多條數(shù)據(jù),并動態(tài)生成表格,請求表單后將表格的數(shù)據(jù)入庫,下面是我改過的代碼,跟實際代碼有些出入,但都是差不多的,只是命名相關的改了一下,第三方接口的代碼下面不會公布出來,請見諒!

二、其中界面很簡單,就一個文本輸入框,輸入關鍵字,一個查詢按鈕,點擊的時候觸發(fā)js事件,并通過ajax請求,還有一個暫時沒有數(shù)據(jù)的表格,查詢后動態(tài)生成的數(shù)據(jù),操作只有一個移除功能,可以移除這條表格的數(shù)據(jù),保存后入庫,這里只貼主要代碼,這里主要通過關鍵字來查找某個組group的用戶信息,具體操作需根據(jù)實際業(yè)務情況:

(1)、html頁面代碼如下:

<form method="post" action="{% url 'user:user_info_add' %}">
{% csrf_token %}
<div>
<input id="key_words" name="key_words" type="text">
<a οnclick="query({{ user_id }})">查詢</a>
</div>

<table>
<thead>
<tr>
<th>姓名</th>
<th>身份證號</th>
<th>手機號</th>
<th>操作</th>
</tr>
</thead>
<tbody id="user_info">
</tbody>
</table>

<button type="submit">保存</button>

(2)、js事件代碼如下:

 <script type="text/javascript">
    function query(user_id){
      var key_words= $('#key_words').val()
      $.ajax({
        type: "post",
        url: "{% url 'user:user_query_info' %}",
        dataType: "json",
        data: JSON.stringify({user_id: user_id, key_words: key_words}),
        success: function (data) {
          for (var i = 0; i < data.length; i++) {
            $('#user_info').append("<tr id='row"+i+"'><input type='hidden' name='row"+ i +"' value='"+i+"'><td>"+ data[i]['name'] + "</td><input type='hidden' name='name"+ i +"' value='"+data[i]['name']+"'><td>"+ data[i]['id_no'] + "</td><input type='hidden' name='id_no"+ i +"' value='"+data[i]['id_no']+"'><td>" + data[i]['mobile_no']+"</td><input type='hidden' name='mobile_no"+ i +"' value='"+data[i]['mobile_no']+"'><td><a οnclick='remove("+i+")'>移除</a></td></tr>")
          }
        }
      });
    }
 
    function remove(i) {
      $('#row'+i).remove()
    }
  </script>

(3)、其中點擊查詢來請求接口,這里django底下的url為user:user_query_info,其中view底下便是查詢所需數(shù)據(jù),并調用接口UserInfoSearch,這個封裝的接口便不提供了,就是封裝參數(shù)請求過去而已,返回響應的數(shù)據(jù)動態(tài)生成表格,主要代碼如下:

from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from json import loads
from user.models.user_model import User
from interface.models import UserInfoSearch
 
 
class QueryUserInfo(View):
  """
  查詢用戶信息
  """
  def post(self, request):
    # 獲取ajax請求過來的data數(shù)據(jù)
    for key in request.POST:
      keydict = eval(key)
      user_id = int(keydict["user_id"])
      user_name = str(keydict["user_name"])
 
    # 獲取用戶相關的數(shù)據(jù)庫數(shù)據(jù),供接口使用
    user_object = User.objects.get(id=user_id)
    group_id = user_object.group_id
    query_id = user_object.query_id
    # 請求搜索用戶信息接口
    user_info_data = loads(UserInfoSearch.get(
      self, request, query_id, group_id, user_name).content)
    user_info_data = loads(user_info_data)
    # 返回成功進行操作,取出相關數(shù)據(jù),并封裝進user_info_list這個列表當中,返回一個JsonResponse對象,通過返回的數(shù)據(jù)動態(tài)生成表格
    if user_info_data['code'] == 0:
      print(user_info_data)
      user_data = user_info_data['data']
      user_info_list = []
      for user in user_data:
        user_list = user['userList']
        for list in user_list:
          user_dict = {}
          user_dict['name'] = list['name']
          for info_list in list['infoList']:
            user_dict['id_no'] = info_list['id_no']
            user_dict['mobile_no'] = info_list['mobile_no']
          user_info_list.append(user_dict)
      print(user_info_list)
    else:
      user_info_list = []
    return JsonResponse(user_info_list, safe=False)
 
  @csrf_exempt
  def dispatch(self, *args, **kwargs):
    return super(QueryUserInfo, self).dispatch(*args, **kwargs)

接口返回成功時,響應的數(shù)據(jù)格式如下:

{
 "code": 0,
 "message": "成功",
 "data": [
  {
   "keywords": "軟件工程",
   "groupId": "10",
   "userList": [
    {
     "name": '林小熊',
     "infoList": [
      {
       "id_no": '4413199509237848',
       "mobile_no": '18565726783'
      }
     ]
    }
 {
     "name": '林大熊',
     "infoList": [
      {
       "id_no": '4413199509837848',
       "mobile_no": '18565726788'
      }
     ]
    }
   ]
  }
 ]
}

(4)、請求接口成功后,如果有響應數(shù)據(jù)的話,就會動態(tài)生成表格,在上面的js底下有封裝了幾個input表單隱藏域,用來保存數(shù)據(jù)使用,主要的思路是把表格底下的每一條數(shù)據(jù)的不同列都通過索引來區(qū)分標記,比如第一行的就分別為row0,name0,id_no0,mobile_no0,以此類推,主要js的代碼如下:

for (var i = 0; i < data.length; i++) {
  $('#user_info').append("<tr id='row"+i+"'><input type='hidden' name='row"+ i +"' value='"+i+"'><td>"+ data[i]['name'] + "</td><input type='hidden' name='name"+ i +"' value='"+data[i]['name']+"'><td>"+ data[i]['id_no'] + "</td><input type='hidden' name='id_no"+ i +"' value='"+data[i]['id_no']+"'><td>" + data[i]['mobile_no']+"</td><input type='hidden' name='mobile_no"+ i +"' value='"+data[i]['mobile_no']+"'><td><a οnclick='remove("+i+")'>移除</a></td></tr>")
}

點擊保存之后,要將返回多條數(shù)據(jù)入庫,而關鍵字是一樣的,關鍵字一樣,但是返回數(shù)據(jù)多天,這里就要篩選處理數(shù)據(jù),主要代碼如下,那些model還有引包的這里就不附上了,這里主要是記錄如何得到所要保存的數(shù)據(jù),篩選過濾數(shù)據(jù):

class UserInfoAddView(View):
  def post(self, request, user_id):
    """
    添加用戶信息
    :param request:
    :param user_id: 用戶表id
    :return:
    """
    key_words = request.POST.get('key_words')
    common_user_data = {'key_words': key_words}
    user_info_list = []
    # 獲取所有表單數(shù)據(jù),但只篩選動態(tài)表格底下的表單隱藏域名稱包含row的,然后通過這個鍵找到其值,然后通過其值找到動態(tài)表格的各個數(shù)據(jù),封裝為字典,并追加到列表底下
    for key, val in request.POST.items():
      user_dict = {}
      if 'row' in key:
        name = request.POST.get('name' + val)
        id_no = request.POST.get('id_no' + val)
        mobile_no = request.POST.get('mobile_no' + val)
        user_dict['name'] = name
        user_dict['id_no'] = id_no
        user_dict['mobile_no'] = mobile_no
  # 這里過濾掉循環(huán)所產(chǎn)生空的字典,有數(shù)據(jù)才追加列表
      if user_dict:
        user_info_list.append(user_dict)
 # 循環(huán)列表底下的字典數(shù)據(jù),并合并公共的數(shù)據(jù)字典,最后入庫
    for user in user_info_list:
      user_data = dict(common_user_data, **user)
      UserInfo.objects.create(**user_data)
    return render(request, '/user/user_info_success.html')

以上這篇Django實現(xiàn)列表頁商品數(shù)據(jù)返回教程就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • python 普通克里金(Kriging)法的實現(xiàn)

    python 普通克里金(Kriging)法的實現(xiàn)

    這篇文章主要介紹了python 普通克里金(Kriging)法的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • Centos5.x下升級python到python2.7版本教程

    Centos5.x下升級python到python2.7版本教程

    這篇文章主要介紹了Centos5.x下升級python到python2.7版本教程,本文使用編譯安裝方式,并配置了一系列需要更改的配置項,需要的朋友可以參考下
    2015-02-02
  • python的endswith()的使用方法及實例

    python的endswith()的使用方法及實例

    這篇文章主要介紹了python的endswith()的使用方法及實例,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-07-07
  • Python 創(chuàng)建新文件時避免覆蓋已有的同名文件的解決方法

    Python 創(chuàng)建新文件時避免覆蓋已有的同名文件的解決方法

    今天小編就為大家分享一篇Python 創(chuàng)建新文件時避免覆蓋已有的同名文件的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • 關于Python正則表達式 findall函數(shù)問題詳解

    關于Python正則表達式 findall函數(shù)問題詳解

    在寫正則表達式的時候總會遇到不少的問題,本文講述了Python正則表達式中 findall()函數(shù)和多個表達式元組相遇的時候會出現(xiàn)的問題
    2018-03-03
  • 學會這個炫酷圖表利器pyecharts,還怕不被公司重用?

    學會這個炫酷圖表利器pyecharts,還怕不被公司重用?

    前段時間,公司高層要看上半年度項目組業(yè)績數(shù)據(jù)分析,沒辦法,硬著頭皮也要上!說到數(shù)據(jù)分析,肯定離不開數(shù)據(jù)的可視化,畢竟圖表比冷冰冰的數(shù)字更加直觀,Boss只想一眼就能看出趨勢和結論.今天我們就聊一聊 pyecharts 中幾種常用的圖表, ,需要的朋友可以參考下
    2021-06-06
  • Python實現(xiàn)針對json中某個關鍵字段進行排序操作示例

    Python實現(xiàn)針對json中某個關鍵字段進行排序操作示例

    這篇文章主要介紹了Python實現(xiàn)針對json中某個關鍵字段進行排序操作,涉及Python json數(shù)組排序及l(fā)ambda表達式相關操作技巧,需要的朋友可以參考下
    2018-12-12
  • Python 格式化打印json數(shù)據(jù)方法(展開狀態(tài))

    Python 格式化打印json數(shù)據(jù)方法(展開狀態(tài))

    今天小編就為大家分享一篇Python 格式化打印json數(shù)據(jù)方法(展開狀態(tài)),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Python中shutil模塊的學習筆記教程

    Python中shutil模塊的學習筆記教程

    shutil模塊是一種高層次的文件操作工具,類似于高級API,主要強大之處在于其對文件的復制與刪除操作更是比較支持好。下面這篇文章主要介紹了Python中shutil模塊的相關教程,需要的朋友可以參考學習,下面來一起看看吧。
    2017-04-04
  • python-視頻分幀&多幀合成視頻實例

    python-視頻分幀&多幀合成視頻實例

    今天小編就為大家分享一篇python-視頻分幀&多幀合成視頻實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12

最新評論

荣昌县| 德化县| 新田县| 岳普湖县| 霞浦县| 阿鲁科尔沁旗| 平江县| 当涂县| 喀什市| 西平县| 翁牛特旗| 金湖县| 彰化县| 汉源县| 曲沃县| 夏邑县| 伊吾县| 句容市| 辉县市| 定安县| 揭阳市| 成都市| 海丰县| 大新县| 亳州市| 宁武县| 恭城| 徐水县| 河间市| 改则县| 紫阳县| 宜兰县| 连州市| 建宁县| 唐山市| 高阳县| 宁南县| 庆元县| 蒙自县| 隆回县| 台中市|