Another means of updating a subset of a model's fields

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.db import connection, transaction

def update(model_instance, *args):
    """
    Updates only specified fields of the given model instance.
    """
    opts = model_instance._meta
    fields = [opts.get_field(f) for f in args]
    db_values = [f.get_db_prep_save(f.pre_save(model_instance, False)) for f in fields]
    if db_values:
        connection.cursor().execute("UPDATE %s SET %s WHERE %s=%%s" % \
            (connection.ops.quote_name(opts.db_table),
             ','.join(['%s=%%s' % connection.ops.quote_name(f.column) for f in fields]),
             connection.ops.quote_name(opts.pk.column)),
             db_values + opts.pk.get_db_prep_lookup('exact', model_instance.pk))
        transaction.commit_unless_managed()

More like this

  1. Update only selected model fields by jcrocholl 4 years, 6 months ago
  2. PositionField by jpwatts 3 years, 10 months ago
  3. Ordered items in the database - alternative by Leonidas 4 years, 11 months ago
  4. UTC DateTime field by ludo 4 years, 9 months ago
  5. SerializedObjectField by dominno 2 years, 2 months ago

Comments

(Forgotten your password?)