在配置類中定義,title字段沒什么意義,這次僅作演示用
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序制作、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了鎮(zhèn)原免費(fèi)建站歡迎大家使用!
list_filter = ["title", "publish", "authors"]
調(diào)用:
filter_condition = self.get_filter_condition(request)
取出數(shù)據(jù):
連續(xù)兩個(gè)filter之間是且的關(guān)系,等于取出符合這兩個(gè)條件的數(shù)據(jù)
data_list = self.model.objects.all().filter(search_condition).filter(filter_condition)
def get_filter_linktag(self):
link_dic = {}
#--------------------數(shù)據(jù)處理邏輯-------------------------
#循環(huán)過濾項(xiàng)列表
for filter_field in self.config.list_filter: #["title", "publish", "authors"]
#獲取request.GET中相應(yīng)是哪個(gè)字段
#舉例:http://127.0.0.1:8000/stark/app01/book/?publish=2
#當(dāng)循環(huán)到publish時(shí)獲取這個(gè)2
cid = self.request.GET.get(filter_field, 0)
#根據(jù)字符串名稱拿字段對(duì)象,self.config是當(dāng)前這張表的配置類實(shí)例對(duì)象
filter_field_obj = self.config.model._meta.get_field(filter_field)
#print("filter_field_obj==>", filter_field_obj)
#得到app01.Book.publish和app01.Book.authors
#拿對(duì)象下面的數(shù)據(jù)
#.rel .to 來自于ForeignKey和ManyToManyField這兩個(gè)類
#.rel可以看到對(duì)象的數(shù)據(jù)類型,加上.to可以拿到對(duì)象下面的數(shù)據(jù),.to只對(duì)一對(duì)一,一對(duì)多,多對(duì)多有效
#print(filter_field_obj.rel.to)
#結(jié)果:
#< class 'app01.models.Publish'>
#< class 'app01.models.Author'>
#判斷當(dāng)前字段對(duì)象是不是一對(duì)多或多對(duì)多類型(需要提前引入這兩個(gè)類),兩種情況取得值也有所不懂
if isinstance(filter_field_obj, ForeignKey) or isinstance(filter_field_obj, ManyToManyField):
#如果是的話就取這個(gè)字段關(guān)聯(lián)的內(nèi)容
data_list = filter_field_obj.rel.to.objects.all() #[publish2, publish3....]
# print("data_list==>", data_list)
# < QuerySet[ < Publish: 圖靈新知 >, < Publish: dzm >, < Publish: 老男孩出版社 >] >
# < QuerySet[ < Author: egon >, < Author: alex >] >
else:#如果不是的話直接取字段對(duì)象的內(nèi)容,這里只取主鍵和當(dāng)前filter_field的值,比如當(dāng)前正好是"title"
data_list = self.config.model.objects.all().values("pk", filter_field)
#print("data_list==>", data_list)
#data_list==> ALL" %params.urlencode()))
else: #如果沒有值
temp.append(mark_safe("ALL"))
#處理數(shù)據(jù)標(biāo)簽
#將data_list循環(huán)起來 < QuerySet[ < Publish: 圖靈新知 >, < Publish: dzm >...] >
for obj in data_list:
#判斷當(dāng)前字段對(duì)象是不是一對(duì)多或多對(duì)多
if isinstance(filter_field_obj, ForeignKey) or isinstance(filter_field_obj, ManyToManyField):
#此時(shí)的obj是一個(gè)個(gè)對(duì)象,取主鍵值和文本內(nèi)容
pk = obj.pk
text = str(obj) #圖靈新知
params[filter_field] = pk #結(jié)果
else: #如果不是
#此時(shí)的obj是QuerySet{'pk': 10, 'title': 'PHP'}
pk = obj.get("pk")
text = obj.get(filter_field)
params[filter_field] = text
#params里面是QueryDict(),所以要做序列化
_url = params.urlencode()
#給選中內(nèi)容加高亮
if cid == str(pk) or cid == text:
link_tag = "%s" % (_url, text)
else:
link_tag = "%s" % (_url, text)
#添加到temp列表
temp.append(mark_safe(link_tag))
#構(gòu)建字典用作返回
link_dic[filter_field] = temp
#{'publish': ["ALL", "圖靈新知"...
return link_dic