Model _meta
API的官方文档 https://docs.djangoproject.com/en/1.10/ref/models/meta/
Field access API
>>> from django.contrib.auth.models import User # A field on the model >>> User._meta.get_field(‘username‘) <django.db.models.fields.CharField: username> # A field from another model that has a relation with the current model >>> User._meta.get_field(‘logentry‘) <ManyToOneRel: admin.logentry> # A non existent field >>> User._meta.get_field(‘does_not_exist‘) Traceback (most recent call last): ... FieldDoesNotExist: User has no field named ‘does_not_exist‘
通过这个field access api的choices可以获取有choice字段的表的内容(元组形式的内容),对于外键字段通过get_choices过去内容的元组的列表
比如在model中有个Customer表
class Customer(models.Model): ‘‘‘客户表‘‘‘ name = models.CharField(max_length=32,verbose_name=‘客户姓名‘,blank=True,null=True) qq = models.CharField(max_length=64,verbose_name=‘QQ‘,unique=True) qq_name = models.CharField(max_length=64,verbose_name=‘QQ名称‘,blank=True,null=True) phone = models.CharField(max_length=64,blank=True,null=True,verbose_name=‘手机号码‘) source_choice = ( (0,‘转介绍‘), (1,‘QQ群‘), (2,‘官网‘), (3,‘百度推广‘), (4,‘51CTO‘), (5,‘知乎‘), (6,‘市场推广‘), ) source = models.SmallIntegerField(verbose_name=‘选择来源‘,choices=source_choice) referral_from = models.CharField(verbose_name=‘介绍人‘,max_length=64,blank=True,null=True) consult_course = models.ForeignKey(‘Course‘,verbose_name=‘咨询课程‘) consultant = models.ForeignKey(‘UserProfile‘,verbose_name=‘顾问‘) content = models.TextField(verbose_name=‘咨询详情‘) status_choices = ( (0, ‘已报名‘), (1, ‘未报名‘), ) status = models.SmallIntegerField(choices=status_choices, default=1) date = models.DateTimeField(auto_now_add=True) memo = models.TextField(verbose_name=‘备注‘,blank=True,null=True) tags = models.ManyToManyField(‘Tag‘)#,blank=True,null=True def __unicode__(self): return self.qq
通过_meta.get_field(‘字段名‘)来获取choice所有的内容
obj = Customer._meta.get_field(‘source‘) print obj.choices #输出的结果为 ( (0,‘转介绍‘),(1,‘QQ群‘), (2,‘官网‘),(3,‘百度推广‘),(4,‘51CTO‘),(5,‘知乎‘),(6,‘市场推广‘), ) #那么得到的这个元组就可以用for循环来获取每个小元组项,然后再前端展示
对外键tags的内容获取,通过get_choices()
obj = Customer._meta.get_field(‘tags‘) print obj.get_choices() #输出的结果为: [(‘‘, ‘---------‘), (1, ‘goser1158‘), (2, ‘haha‘)] #同样也可以对列表进行for循环获取里面的小元组来展现到前端页面
当然还可以外键字段获取外键的名称
obj = Customer._meta.get_field(‘consultant‘) print type(obj).__name__ #输出的结果为: ‘ForeignKey‘ obj = Customer._meta.get_field(‘tags‘) print type(obj).__name__ #输出的结果为: ‘ManyToManyField‘ #通过判断外键的名称就可以做进一步的处理操作
时间: 2024-11-28 23:23:04