Django如何从Model中获取字段名称——verbose_name

# models.py

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
# ########################### 处理请求的方法  #############
    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字段名称。

 

转载自:https://blog.csdn.net/qq_16171671/article/details/124027505

posted on 2022-07-28 21:01  一先生94  阅读(839)  评论(0编辑  收藏  举报

导航