Check for None in replaces and replaced_by

Since these are just datastore keys they could have the value 0. Check
for None explicitly.
Fix bug with inverting dependencies

We calculate the dependency graph after updating the database to contain
new dependencies. If any dependencies are inverted in the template with
respect to the old one, this could cause a circular dependency as both
sets of reverse dependencies were added.

The two possible solutions are to calculate the dependencies before
updating any of the existing resources, or to ignore the 'requirers'
list (which has been updated with the new template data) and just base
the reverse dependencies on the requirements list. I chose the latter
because it makes the code tidier.