Options.get_field(field_name)
根据给出的field_name返回一个字段实例。field_name可以是model中的字段,抽象或者继承model的字段,或者指向一个model的另一个model上的字段,最后这种情况中的field_name是用户定义的related_name或者是Django自动产生的名字。note:隐藏的字段不能通过名字检索。如果给出的字段名找不到,会抛出FieldDoesNotExist的错误。
>>> 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'
2. 检索一个model的所有字段实例
Options.get_fields(include_parents=True, include_hidden=False)
以元组的形式返回一个model的相关的所有字段。get_fields接收两个参数用来控制要返回哪些字段。
>>> from django.contrib.auth.models import User
>>> User._meta.get_fields()
(<ManyToOneRel: admin.logentry>,
<django.db.models.fields.AutoField: id>,
<django.db.models.fields.CharField: password>,
<django.db.models.fields.DateTimeField: last_login>,
<django.db.models.fields.BooleanField: is_superuser>,
<django.db.models.fields.CharField: username>,
<django.db.models.fields.CharField: first_name>,
<django.db.models.fields.CharField: last_name>,
<django.db.models.fields.EmailField: email>,
<django.db.models.fields.BooleanField: is_staff>,
<django.db.models.fields.BooleanField: is_active>,
<django.db.models.fields.DateTimeField: date_joined>,
<django.db.models.fields.related.ManyToManyField: groups>,
<django.db.models.fields.related.ManyToManyField: user_permissions>)
原文链接:https://docs.djangoproject.com/en/2.0/ref/models/meta/