This function will take a model instance and return an insert statement for it. I use it for extracting a subset of my production data so that I can reproduce problems in a local environment. The quoting is for mysql, you may have to change it depending on your db backend. Also, it assumes the 'default' database.
1 2 3 4 5 6 7 8 9 10 | def _object_to_query(obj):
values = [(f, '\'%s\'' % f.get_db_prep_save(f.value_from_object(obj))) for f in obj._meta.local_fields]
q = sql.InsertQuery(obj)
q.insert_values(values)
compiler = q.get_compiler('default')
# Normally, execute sets this, but we don't want to call execute
setattr(compiler, 'return_id', False)
stmt, params = compiler.as_sql()
stmt = stmt % params
return stmt
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.