Login

model instance to sql insert statement

Author:
gsoltis
Posted:
December 24, 2010
Language:
Python
Version:
1.2
Tags:
sql model db
Score:
1 (after 1 ratings)

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

  1. print SQL statements by zuzelvp 5 years, 4 months ago
  2. Simple solution for model schema evolution / database changelog by kahless 8 years ago
  3. Table Creation Using ORM Standalone by EliAndrewC 7 years, 4 months ago
  4. Another means of updating a subset of a model's fields by insin 7 years, 7 months ago
  5. Save a model using an arbitrary db connection by weswinham 5 years, 10 months ago

Comments

Please login first before commenting.