Model _meta API

  • class Options[source]
  • The model _meta API is at the core of the Django ORM. It enables otherparts of the system such as lookups, queries, forms, and the admin tounderstand the capabilities of each model. The API is accessible throughthe _meta attribute of each model class, which is an instance of andjango.db.models.options.Options object.

Methods that it provides can be used to:

  • Retrieve all field instances of a model
  • Retrieve a single field instance of a model by name

Field access API

Retrieving a single field instance of a model by name

  • Options.getfield(_field_name)[source]
  • Returns the field instance given a name of a field.

field_name can be the name of a field on the model, a fieldon an abstract or inherited model, or a field defined on anothermodel that points to the model. In the latter case, the field_namewill be the related_name defined by the user or the name automaticallygenerated by Django itself.

Hidden fields cannot be retrievedby name.

If a field with the given name is not found aFieldDoesNotExist exception will beraised.

  1. >>> from django.contrib.auth.models import User
  2.  
  3. # A field on the model
  4. >>> User._meta.get_field('username')
  5. <django.db.models.fields.CharField: username>
  6.  
  7. # A field from another model that has a relation with the current model
  8. >>> User._meta.get_field('logentry')
  9. <ManyToOneRel: admin.logentry>
  10.  
  11. # A non existent field
  12. >>> User._meta.get_field('does_not_exist')
  13. Traceback (most recent call last):
  14. ...
  15. FieldDoesNotExist: User has no field named 'does_not_exist'

Retrieving all field instances of a model

  • Options.getfields(_include_parents=True, include_hidden=False)[source]
  • Returns a tuple of fields associated with a model. get_fields() acceptstwo parameters that can be used to control which fields are returned:

    • include_parents
    • True by default. Recursively includes fields defined on parentclasses. If set to False, get_fields() will only search forfields declared directly on the current model. Fields from models thatdirectly inherit from abstract models or proxy classes are consideredto be local, not on the parent.
    • include_hidden
    • False by default. If set to True, get_fields() will includefields that are used to back other field's functionality. This willalso include any fields that have a related_name (suchas ManyToManyField, orForeignKey) that start with a "+".
  1. >>> from django.contrib.auth.models import User
  2. >>> User._meta.get_fields()
  3. (<ManyToOneRel: admin.logentry>,
  4. <django.db.models.fields.AutoField: id>,
  5. <django.db.models.fields.CharField: password>,
  6. <django.db.models.fields.DateTimeField: last_login>,
  7. <django.db.models.fields.BooleanField: is_superuser>,
  8. <django.db.models.fields.CharField: username>,
  9. <django.db.models.fields.CharField: first_name>,
  10. <django.db.models.fields.CharField: last_name>,
  11. <django.db.models.fields.EmailField: email>,
  12. <django.db.models.fields.BooleanField: is_staff>,
  13. <django.db.models.fields.BooleanField: is_active>,
  14. <django.db.models.fields.DateTimeField: date_joined>,
  15. <django.db.models.fields.related.ManyToManyField: groups>,
  16. <django.db.models.fields.related.ManyToManyField: user_permissions>)
  17.  
  18. # Also include hidden fields.
  19. >>> User._meta.get_fields(include_hidden=True)
  20. (<ManyToOneRel: auth.user_groups>,
  21. <ManyToOneRel: auth.user_user_permissions>,
  22. <ManyToOneRel: admin.logentry>,
  23. <django.db.models.fields.AutoField: id>,
  24. <django.db.models.fields.CharField: password>,
  25. <django.db.models.fields.DateTimeField: last_login>,
  26. <django.db.models.fields.BooleanField: is_superuser>,
  27. <django.db.models.fields.CharField: username>,
  28. <django.db.models.fields.CharField: first_name>,
  29. <django.db.models.fields.CharField: last_name>,
  30. <django.db.models.fields.EmailField: email>,
  31. <django.db.models.fields.BooleanField: is_staff>,
  32. <django.db.models.fields.BooleanField: is_active>,
  33. <django.db.models.fields.DateTimeField: date_joined>,
  34. <django.db.models.fields.related.ManyToManyField: groups>,
  35. <django.db.models.fields.related.ManyToManyField: user_permissions>)

Migrating from the old API

As part of the formalization of the Model._meta API (from thedjango.db.models.options.Options class), a number of methods andproperties have been deprecated and will be removed in Django 1.10.

These old APIs can be replicated by either:

  • invoking Options.get_field(), or;
  • invoking Options.get_fields() to retrieve a list of allfields, and then filtering this list using the field attributes that describe (or retrieve, in the case of_with_model variants) the properties of the desired fields.Although it's possible to make strictly equivalent replacements of the oldmethods, that might not be the best approach. Taking the time to refactor anyfield loops to make better use of the new API - and possibly include fieldsthat were previously excluded - will almost certainly result in better code.

Assuming you have a model named MyModel, the following substitutionscan be made to convert your code to the new API:

  • MyModel._meta.get_field(name) becomes:
  1. f = MyModel._meta.get_field(name)

then check if:

  • f.auto_created == False, because the new get_field()API will find "reverse" relations, and:
  • f.is_relation and f.related_model is None, because the newget_field() API will findGenericForeignKey relations.

    • MyModel._meta.get_field_by_name(name) returns a tuple of these fourvalues with the following replacements:
  • field can be found by MyModel._meta.get_field(name)

  • model can be found through themodel attribute on the field.

  • direct can be found by: not field.auto_created or field.concrete

The auto_created check excludesall "forward" and "reverse" relations that are created by Django, butthis also includes AutoField and OneToOneField on proxy models.We avoid filtering out these attributes using theconcrete attribute.

  • m2m can be found through themany_to_many attribute on the field.
  • MyModel._meta.get_fields_with_model() becomes:
  1. [
  2. (f, f.model if f.model != MyModel else None)
  3. for f in MyModel._meta.get_fields()
  4. if not f.is_relation
  5. or f.one_to_one
  6. or (f.many_to_one and f.related_model)
  7. ]
  • MyModel._meta.get_concrete_fields_with_model() becomes:
  1. [
  2. (f, f.model if f.model != MyModel else None)
  3. for f in MyModel._meta.get_fields()
  4. if f.concrete and (
  5. not f.is_relation
  6. or f.one_to_one
  7. or (f.many_to_one and f.related_model)
  8. )
  9. ]
  • MyModel._meta.get_m2m_with_model() becomes:
  1. [
  2. (f, f.model if f.model != MyModel else None)
  3. for f in MyModel._meta.get_fields()
  4. if f.many_to_many and not f.auto_created
  5. ]
  • MyModel._meta.get_all_related_objects() becomes:
  1. [
  2. f for f in MyModel._meta.get_fields()
  3. if (f.one_to_many or f.one_to_one)
  4. and f.auto_created and not f.concrete
  5. ]
  • MyModel._meta.get_all_related_objects_with_model() becomes:
  1. [
  2. (f, f.model if f.model != MyModel else None)
  3. for f in MyModel._meta.get_fields()
  4. if (f.one_to_many or f.one_to_one)
  5. and f.auto_created and not f.concrete
  6. ]
  • MyModel._meta.get_all_related_many_to_many_objects() becomes:
  1. [
  2. f for f in MyModel._meta.get_fields(include_hidden=True)
  3. if f.many_to_many and f.auto_created
  4. ]
  • MyModel._meta.get_all_related_m2m_objects_with_model() becomes:
  1. [
  2. (f, f.model if f.model != MyModel else None)
  3. for f in MyModel._meta.get_fields(include_hidden=True)
  4. if f.many_to_many and f.auto_created
  5. ]
  • MyModel._meta.get_all_field_names() becomes:
  1. from itertools import chain
  2. list(set(chain.from_iterable(
  3. (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
  4. for field in MyModel._meta.get_fields()
  5. # For complete backwards compatibility, you may want to exclude
  6. # GenericForeignKey from the results.
  7. if not (field.many_to_one and field.related_model is None)
  8. )))

This provides a 100% backwards compatible replacement, ensuring that bothfield names and attribute names ForeignKeys are included, but fieldsassociated with GenericForeignKeys are not. A simpler version would be:

  1. [f.name for f in MyModel._meta.get_fields()]

While this isn't 100% backwards compatible, it may be sufficient in manysituations.