Django實(shí)現(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實(shí)現(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ù)信息了

補(bǔ)充知識:django通過ajax請求接口返回多條數(shù)據(jù),并動態(tài)生成表格,請求表單后將表格數(shù)據(jù)并入庫
一、最近在做接口相關(guān)的開發(fā),需求是這樣的,通過一個接口所需要傳遞的參數(shù),調(diào)用接口后,處理接口響應(yīng)的參數(shù),返回多條數(shù)據(jù),并動態(tài)生成表格,請求表單后將表格的數(shù)據(jù)入庫,下面是我改過的代碼,跟實(shí)際代碼有些出入,但都是差不多的,只是命名相關(guān)的改了一下,第三方接口的代碼下面不會公布出來,請見諒!
二、其中界面很簡單,就一個文本輸入框,輸入關(guān)鍵字,一個查詢按鈕,點(diǎn)擊的時候觸發(fā)js事件,并通過ajax請求,還有一個暫時沒有數(shù)據(jù)的表格,查詢后動態(tài)生成的數(shù)據(jù),操作只有一個移除功能,可以移除這條表格的數(shù)據(jù),保存后入庫,這里只貼主要代碼,這里主要通過關(guān)鍵字來查找某個組group的用戶信息,具體操作需根據(jù)實(shí)際業(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>手機(jī)號</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)、其中點(diǎn)擊查詢來請求接口,這里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>")
}
點(diǎn)擊保存之后,要將返回多條數(shù)據(jù)入庫,而關(guān)鍵字是一樣的,關(guān)鍵字一樣,但是返回?cái)?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實(shí)現(xiàn)列表頁商品數(shù)據(jù)返回教程就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python 普通克里金(Kriging)法的實(shí)現(xiàn)
這篇文章主要介紹了python 普通克里金(Kriging)法的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Centos5.x下升級python到python2.7版本教程
這篇文章主要介紹了Centos5.x下升級python到python2.7版本教程,本文使用編譯安裝方式,并配置了一系列需要更改的配置項(xiàng),需要的朋友可以參考下2015-02-02
python的endswith()的使用方法及實(shí)例
這篇文章主要介紹了python的endswith()的使用方法及實(shí)例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07
Python 創(chuàng)建新文件時避免覆蓋已有的同名文件的解決方法
今天小編就為大家分享一篇Python 創(chuàng)建新文件時避免覆蓋已有的同名文件的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11
關(guān)于Python正則表達(dá)式 findall函數(shù)問題詳解
在寫正則表達(dá)式的時候總會遇到不少的問題,本文講述了Python正則表達(dá)式中 findall()函數(shù)和多個表達(dá)式元組相遇的時候會出現(xiàn)的問題2018-03-03
學(xué)會這個炫酷圖表利器pyecharts,還怕不被公司重用?
前段時間,公司高層要看上半年度項(xiàng)目組業(yè)績數(shù)據(jù)分析,沒辦法,硬著頭皮也要上!說到數(shù)據(jù)分析,肯定離不開數(shù)據(jù)的可視化,畢竟圖表比冷冰冰的數(shù)字更加直觀,Boss只想一眼就能看出趨勢和結(jié)論.今天我們就聊一聊 pyecharts 中幾種常用的圖表, ,需要的朋友可以參考下2021-06-06
Python實(shí)現(xiàn)針對json中某個關(guān)鍵字段進(jìn)行排序操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)針對json中某個關(guān)鍵字段進(jìn)行排序操作,涉及Python json數(shù)組排序及l(fā)ambda表達(dá)式相關(guān)操作技巧,需要的朋友可以參考下2018-12-12
Python 格式化打印json數(shù)據(jù)方法(展開狀態(tài))
今天小編就為大家分享一篇Python 格式化打印json數(shù)據(jù)方法(展開狀態(tài)),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python中shutil模塊的學(xué)習(xí)筆記教程
shutil模塊是一種高層次的文件操作工具,類似于高級API,主要強(qiáng)大之處在于其對文件的復(fù)制與刪除操作更是比較支持好。下面這篇文章主要介紹了Python中shutil模塊的相關(guān)教程,需要的朋友可以參考學(xué)習(xí),下面來一起看看吧。2017-04-04

