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,
      referred = getattr(model,
      if referred is not None:
                   '%s.%s' % (name,, dict)
      dict['%s.%s' % (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:
      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.