Skip to content

Instantly share code, notes, and snippets.

@PirosB3
Created September 6, 2014 10:28
Show Gist options
  • Save PirosB3/0e02ae6fc9db02ce2d14 to your computer and use it in GitHub Desktop.
Save PirosB3/0e02ae6fc9db02ce2d14 to your computer and use it in GitHub Desktop.
def get_field(self, field_name, **kwargs):
"""
Returns a field instance given a field name. By default will only search in forward
fields. By setting the include_related flag, the search is also extended to reverse
relations.
"""
if not apps.ready:
warnings.warn(
"The Apps registry is still not ready, this means get_field() is not able "
"to find related objects that point to this model.",
AppsNotReadyWarning <--- IS THIS ANY GOOD?
)
field_map = self.all_fields_map if apps.ready else self.concrete_fields_map
# NOTE: previous get_field API had a many_to_many key. This key
# has now become m2m. In order to avoid breaking other's implementation
# we will catch the use of 'many_to_many'.
if 'many_to_many' in kwargs:
# If no many_to_many fields are wanted, create a new dictionary with
# without ManyToManyField instances.
if kwargs['many_to_many'] is False:
field_map = dict((name, field) for name, field in six.iteritems(field_map)
if not isinstance(field, ManyToManyField))
# We always want to throw a warning if many_to_many is used regardless
# of if it alters the return type or not.
warnings.warn(
"The 'many_to_many' argument on get_field() will be soon "
"deprecated. Please change your implementation accordingly.",
RemovedInDjango20Warning
)
try:
# Retreive field instance by name from cached or just-computer field map
return field_map[field_name]
except KeyError:
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment