Skip to content

Instantly share code, notes, and snippets.

@sapegin
Created February 9, 2012 13:01
Show Gist options
  • Save sapegin/1779848 to your computer and use it in GitHub Desktop.
Save sapegin/1779848 to your computer and use it in GitHub Desktop.
Springhare JSONP API part
def get_exportable_objects(objects, field_groups=None):
return [get_exportable_object(object, field_groups) for object in objects]
def get_exportable_object(object, field_groups=None):
"""Gathering information about public fields."""
# Primary model
data = parse_exportable_fields(object, field_groups)
# Related models
for relation in object._meta.get_all_related_objects():
if hasattr(relation.model, 'exportable'):
model_name = relation.model._meta.module_name
if hasattr(object, model_name):
data.update(parse_exportable_fields(getattr(object, model_name), field_groups, model_name))
return data
def parse_exportable_fields(model, field_groups=None, prefix=None):
data = {}
for field_name in get_exportable_fields(model, field_groups):
key = '%s_%s' % (prefix, field_name) if prefix else field_name
data[key] = getattr(model, field_name)
return data
def get_exportable_fields(model, groups=None):
if not hasattr(model, 'exportable'): return []
all_groups = model.exportable
if not groups:
return all_groups['default'] if 'default' in all_groups else []
if isinstance(groups, str): groups = [groups]
fields = []
for group in groups:
if group not in all_groups: continue
for field in all_groups[group]:
if field not in fields:
fields.append(field)
return fields
class Gallery(models.Model):
exportable = {
'default': ('title', 'status', 'is_system',),
'short': ('title', 'status', 'is_system',),
'admin': ('title', 'status', 'is_system', 'language', 'level',),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment