from django.db.models.fields import FieldDoesNotExist
import copy
from django.db.models.fields.related import ForeignKey
def get_field(self, name, many_to_many=True):
"""
Returns the requested field by name. Raises FieldDoesNotExist on error.
"""
to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
if hasattr(self, '_copy_fields'):
to_search += self._copy_fields
for f in to_search:
if f.name == name:
return f
if not name.startswith('__') and '__' in name:
f = None
model = self
path = name.split('__')
for field_name in path:
f = model._get_field(field_name)
if isinstance(f, ForeignKey):
model = f.rel.to._meta
f = copy.deepcopy(f)
f.name = name
if not hasattr(self, "_copy_fields"):
self._copy_fields = list()
self._copy_fields.append(f)
return f
raise FieldDoesNotExist, '%s has no field named %r' % (self.object_name, name)
setattr(options.Options, '_get_field', options.Options.get_field.im_func)
setattr(options.Options, 'get_field', get_field)
Comments
I have problems in the setattr. Where i should put that? In my class Model, doesn´t recognize options. Thanks
#
I put the setattr call in the admin.py for my app.
#
I think he means that you get the error 'name 'options' is not defined'
Is there a missing 'from django.db.models import options'?
#
Sorry, yes that import should be there so that options will be recognized
#
i don't really understand how to use it. who calls get_field?
#