def write_models(model, data, field):
written = []<EOL>for hash_ in data:<EOL><INDENT>if field:<EOL><INDENT>if field not in hash_:<EOL><INDENT>raise KeyError(("<STR_LIT>"<EOL>"<STR_LIT>") % field)<EOL><DEDENT>model_kwargs = {field: hash_[field]}<EOL>model_obj = model.objects.get(**model_kwargs)<EOL>for to_set, val in hash_.items():<EOL><INDENT>setattr(model_obj, to_set, val)<EOL><DEDENT>model_obj.save()<EOL><DEDENT>else:<EOL><INDENT>model_obj = model.objects.create(**hash_)<EOL><DEDENT>written.append(model_obj)<EOL><DEDENT>reset_sequence(model)<EOL>return written<EOL>
:param model: a Django model class
:param data: a list of hashes to build models from
:param field: a field name to match models on, or None
:returns: a list of models written

Create or update models for each data hash.

`field` is the field that is used to get the existing models out of
the database to update them; otherwise, if ``field=None``, new models are
created.

Useful when registering custom tests with :func:`writes_models`.