Django實現(xiàn)列表頁商品數(shù)據(jù)返回教程
采用的是cbv方式,cbv就是在url中一個路徑對應(yīng)一個類
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格式轉(zhuǎn)成python字符串
return HttpResponse(content,"application/json")
在urls.py文件中配置函數(shù)對應(yīng)的路由
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ù)并入庫
一、最近在做接口相關(guān)的開發(fā),需求是這樣的,通過一個接口所需要傳遞的參數(shù),調(diào)用接口后,處理接口響應(yīng)的參數(shù),返回多條數(shù)據(jù),并動態(tài)生成表格,請求表單后將表格的數(shù)據(jù)入庫,下面是我改過的代碼,跟實際代碼有些出入,但都是差不多的,只是命名相關(guān)的改了一下,第三方接口的代碼下面不會公布出來,請見諒!
二、其中界面很簡單,就一個文本輸入框,輸入關(guān)鍵字,一個查詢按鈕,點擊的時候觸發(fā)js事件,并通過ajax請求,還有一個暫時沒有數(shù)據(jù)的表格,查詢后動態(tài)生成的數(shù)據(jù),操作只有一個移除功能,可以移除這條表格的數(shù)據(jù),保存后入庫,這里只貼主要代碼,這里主要通過關(guān)鍵字來查找某個組group的用戶信息,具體操作需根據(jù)實際業(yè)務(wù)情況:
(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ù),并調(diào)用接口UserInfoSearch,這個封裝的接口便不提供了,就是封裝參數(shù)請求過去而已,返回響應(yīng)的數(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"])
# 獲取用戶相關(guān)的數(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)
# 返回成功進(jìn)行操作,取出相關(guān)數(shù)據(jù),并封裝進(jìn)user_info_list這個列表當(dāng)中,返回一個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)
接口返回成功時,響應(yīng)的數(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)、請求接口成功后,如果有響應(yīng)數(shù)據(jù)的話,就會動態(tài)生成表格,在上面的js底下有封裝了幾個input表單隱藏域,用來保存數(shù)據(jù)使用,主要的思路是把表格底下的每一條數(shù)據(jù)的不同列都通過索引來區(qū)分標(biāo)記,比如第一行的就分別為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ù)入庫,而關(guān)鍵字是一樣的,關(guān)鍵字一樣,但是返回數(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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中使用Opencv開發(fā)停車位計數(shù)器功能
這篇文章主要介紹了Python中使用Opencv開發(fā)停車位計數(shù)器,本教程最好的一點就是我們將使用基本的圖像處理技術(shù)來解決這個問題,沒有使用機器學(xué)習(xí)、深度學(xué)習(xí)進(jìn)行訓(xùn)練來識別,感興趣的朋友跟隨小編一起看看吧2022-04-04
利用python微信庫itchat實現(xiàn)微信自動回復(fù)功能
最近發(fā)現(xiàn)了一個特別好玩的Python 微信庫itchat,可以實現(xiàn)自動回復(fù)等多種功能,下面這篇文章主要給大家介紹了利用python微信庫itchat實現(xiàn)微信自動回復(fù)功能的相關(guān)資料,需要的朋友可以參考學(xué)習(xí),下面來一起看看吧。2017-05-05
Python強化練習(xí)之Tensorflow2 opp算法實現(xiàn)月球登陸器
在面向?qū)ο蟪霈F(xiàn)之前,我們采用的開發(fā)方法都是面向過程的編程(OPP)。面向過程的編程中最常用的一個分析方法是“功能分解”。我們會把用戶需求先分解成模塊,然后把模塊分解成大的功能,再把大的功能分解成小的功能,整個需求就是按照這樣的方式,最終分解成一個一個的函數(shù)2021-10-10
Windows下pycharm安裝第三方庫失敗(通用解決方案)
這篇文章主要介紹了Windows下pycharm安裝第三方庫失敗(通用解決方案),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

