Fix weird IntegrityErrors

For some reason, merging (and possibly creating) an object that has
foreign keys specified as objects, not actual primary key values, causes
IntegrityErrors sometimes. I don't understand why. I don't understand
why this commit fixes it. There's a lot I don't understand about
SQLAlchemy.