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