Cast to db_value for insert queries

I was getting problems with foreign key fields not being cast properly, looks like this is the solution. It's not well tested so you might want to have a play yourself before accepting.

Thanks,
Alex