Saturday 27 April 2013

Serialise a Django model to a dictionary following links

To enable a simple templating system I wanted a dictionary with keys as dotted paths in the object tree eg child.carer.user.first_name, however Django does not offer the ability to follow foreign keys out of the box.

def dottedDict(model, name, dict):
  for f in model._meta.fields:
    if type(f) in [models.fields.related.ForeignKey,
                   models.fields.related.OneToOneField]:
      referred = getattr(model, f.name)
      if referred is not None:
        dottedDict(referred, 
                   '%s.%s' % (name, f.name), dict)
    else:
      dict['%s.%s' % (name, f.name)] = 
          model.__dict__[f.name]
  return dict

This enables an object to be rendered (substituting empty strings for nulls):

def registrationFormLatex(self):
  template = file('Form.tex.template', 'r').read()
  dotted = dottedDict(self, 'child', {})
  done = False
  while not done:
    try:
      page = template % dotted
      done = True
    except KeyError, e:
      dotted[e.message] = ''
  return page

Tuesday 9 April 2013

Angelica in the News

Article from The News, Saturday May 11 1991.
pdf