Django


1199 浏览 5 years, 5 months

4.5 属性的获取

版权声明: 转载请注明出处 http://www.codingsoho.com/

属性的获取

用例名为inst,类名为cls

  • 从instance获取类名
inst.__class__.__name__ 
  • 从instance获取key值
inst._get_pk_val()
  • 从类获取fields的名字
cls._meta.get_all_field_names():

1.8之后改为

model._meta.get_fields()

获取到的是model query,所以通常做法是这样的:

[f.name for f in MyModel._meta.get_fields()]
  • 从类获取fields
cls._meta.get_field(fieldname)
  • 判断field是否是文件
isinstance(field, FileField)
  • 获取field显示(针对selection,choice的field)
inst._get_FIELD_display(field)
  • 获取model fields label and help_text
class ContactData(models.Model):
    name  = models.CharField(max_length=300, verbose_name=u"Name", help_text=u"Please enter your name...",null=True, blank=False)
    phone = models.CharField(max_length=300, verbose_name=u"Phone number", null=True, blank=False)

unicode(ContactData._meta.get_field('name').verbose_name)
unicode(ContactData._meta.get_field('name').help_text)
  • 从field获取model和关联model field.model field.related_model

  • 其他用法,待验证

get_m2m_with_model
related_objects
get_fields_with_model
get_concrete_fields_with_model
get_all_related_objects
get_all_related_objects_with_model
get_all_related_many_to_many_objects
get_all_related_m2m_objects_with_model