django中Model _meta API
阿新 • • 發佈:2017-08-06
cut () key source manytoone ocs urn blank pre
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‘ #通過判斷外鍵的名稱就可以做進一步的處理操作
django中Model _meta API