Skip to content

Commit

Permalink
Add common utility functions
Browse files Browse the repository at this point in the history
The process of fetching a distantly related field type (for the purpose
of verifying its existence/validity or for actually getting the type
itself) was repeated in a few places in the project code.
  • Loading branch information
tiliv committed Jan 17, 2013
1 parent 7c9ea7f commit 6c4f508
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions datatableview/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from django.utils.encoding import StrAndUnicode
from django.template.loader import render_to_string
from django.db.models.fields import FieldDoesNotExist

# Sane boundary constants
MINIMUM_PAGE_LENGTH = 5
Expand Down Expand Up @@ -31,6 +32,40 @@
'sort_column_direction': 'sSortDir_%d',
}

def resolve_orm_path(model, orm_path):
"""
Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the
path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will
be raised.
"""

bits = orm_path.split('__')
endpoint_model = reduce(get_model_at_related_field, [model] + bits[:-1])
field, _, _, _ = endpoint_model._meta.get_field_by_name(bits[-1])
return field

def get_model_at_related_field(model, attr):
"""
Looks up ``attr`` as a field of ``model`` and returns the related model class. If ``attr`` is
not a relationship field, ``ValueError`` is raised.
"""

try:
field, _, direct, m2m = model._meta.get_field_by_name(attr)
except FieldDoesNotExist:
raise

if m2m:
model = field.field.rel.to
elif direct:
model = field.related.model
else:
raise ValueError("{}.{} ({}) is not a relationship field.".format(model.__name__, attr,
field.__class__.__name__))
return model

class DatatableStructure(StrAndUnicode):
"""
A class designed to be echoed directly to into template HTML to represent a skeleton table
Expand Down

0 comments on commit 6c4f508

Please sign in to comment.