1. 程式人生 > >Django如何從Model中獲取字段名稱——verbose_name

Django如何從Model中獲取字段名稱——verbose_name

blog color 學習 url post 定義 ole app war

一、背景

CRM項目重新總結一下,重寫之前的項目發現有不少知識點已經忘記,所以特此來重新總結一下一便後續能夠回憶起

二、代碼分析

1. 核心代碼

from django.conf.urls import url
from django.shortcuts import HttpResponse,render

class VbcConfig(object):
    list_display = []
    def __init__(self,model_class,site):
        self.model_class = model_class   
        self.site 
= site def get_urls(self): app_model_name = (self.model_class._meta.app_label,self.model_class._meta.model_name,) url_pattern = [ url(r^$,self.change_list_view,name=%s_%s_change_list%app_model_name), url(r^add/$,self.add_view,name=%s_%s_add%app_model_name), url(r
^(\d+)/change/$,self.change_view,name=%s_%s_change%app_model_name), url(r^(\d+)/delete/$,self.delete_view,name=%s_%s_delete%app_model_name), ] return url_pattern @property def urls(self): return self.get_urls() # ########################### 處理請求的方法 #############
def change_list_view(self,request,*args,**kwargs): # 處理表頭 head_list = [] for field_name in self.list_display: if isinstance(field_name,str): verbose_name= self.model_class._meta.get_field(field_name).verbose_name else: verbose_name = field_name(self,is_header=True) head_list.append(verbose_name) # 處理數據 data_list = self.model_class.objects.all() new_data_list = [] for row in data_list: temp =[] for field_name in self.list_display: if isinstance(field_name,str): val = getattr(row,field_name) else: val = field_name(self,row) temp.append(val) new_data_list.append(temp) return render(request,changelist.html,{new_data_list:new_data_list,head_list:head_list}) def add_view(self,request,*args,**kwargs): return HttpResponse(添加) def change_view(self,request,*args,**kwargs): return HttpResponse(修改) def delete_view(self,request,*args,**kwargs): return HttpResponse(刪除) class VbcSite(object): def __init__(self): self._registry = {} def registry(self,model_class,vbc_config_class=None): if not vbc_config_class: vbc_config_class = VbcConfig # 如果沒有自定義Config類則實例化VbcConfig類 self._registry[model_class] = vbc_config_class(model_class,self) # 將數據庫model傳入進來進行實例化 def get_urls(self): url_pattern = [] for model_class,vbc_config_obj in self._registry.items(): print(model_class,vbc_config_obj) # 為每一個類,創建4個url """ /stark/app01/userinfo/ /stark/app01/userinfo/add /stark/app01/userinfo/(\d+)/change/ /stark/app01/userinfo/(\d+)/delete/ """ app_name = model_class._meta.app_label model_name = model_class._meta.model_name curd_url = url(r%s/%s/%(app_name,model_name),(vbc_config_obj.urls,None,None)) url_pattern.append(curd_url) return url_pattern @property def urls(self): return (self.get_urls(),None,vbc) site = VbcSite()

2. 實例化model類

from django.shortcuts import HttpResponse
from django.utils.safestring import mark_safe
from stark.service import v1
from app01 import models

class UserInfoConfig(v1.VbcConfig):
    def checkbox(self,obj=None,is_header=False):
        if is_header:
            return 序號
        return mark_safe("<input  type=‘checkbox‘ name=‘pk‘ value=‘%s‘></>"%obj.id)
    def edit(self,obj=None,is_header=False):
        if is_header:
            return 操作
        return mark_safe(<a href="/edit/%s">編輯</a>%obj.id)

    def delete(self,obj=None,is_header=False):
        if is_header:
            return 表頭
        return mark_safe(<a href="/edit/%s">刪除</a>%obj.id)
    list_display = [checkbox,id,name,edit,delete]


class RoleConfig(v1.VbcConfig):

    list_display = [id,title]

class UserTypefig(v1.VbcConfig):

    list_display = [id,title]


v1.site.registry(models.UserInfo,UserInfoConfig)
v1.site.registry(models.UserType,UserTypefig)
v1.site.registry(models.Role,RoleConfig)

三. 學習的知識點:如何從model中獲取字段名稱

1. model

from django.db import models

# Create your models here.

class UserInfo(models.Model):
    name = models.CharField(max_length=32,verbose_name=用戶名)

    def __str__(self):
        return self.name

class Role(models.Model):
    title = models.CharField(max_length=32,verbose_name=用戶角色)
    users = models.ForeignKey(to=UserInfo,verbose_name=用戶職位,on_delete=models.CASCADE)

    def __str__(self):
        return self.title


class UserType(models.Model):
    title = models.CharField(max_length=32,verbose_name=用戶類型)

    def __str__(self):
        return self.title

2. 代碼

# ########################### 處理請求的方法  #############
    def change_list_view(self,request,*args,**kwargs):

        # 處理表頭
        head_list = []
        for field_name in self.list_display:
            if isinstance(field_name,str):
                verbose_name= self.model_class._meta.get_field(field_name).verbose_name   # 在_meta中有個get_field方法,通過將model字段名稱傳入進去,最後執行.verbose_name就可以獲取model字段名稱
            else:
                verbose_name = field_name(self,is_header=True)
            head_list.append(verbose_name)

        # 處理數據
        data_list = self.model_class.objects.all()

        new_data_list = []
        for row in data_list:
            temp =[]
            for field_name in self.list_display:
                if isinstance(field_name,str):
                    val = getattr(row,field_name)
                else:
                    val = field_name(self,row)
                temp.append(val)

            new_data_list.append(temp)

        return render(request,changelist.html,{new_data_list:new_data_list,head_list:head_list})

小結:

self.model_class._meta.get_field(field_name).verbose_name   
# 在_meta中有個get_field方法,通過將model字段名稱傳入進去,最後執行.verbose_name就可以獲取model字段名稱

Django如何從Model中獲取字段名稱——verbose_name