Login

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

Author:
insin
Posted:
November 23, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

Based on the UPDATE query section of Model.save(), this is another means of limiting the fields which are used in an UPDATE statement and bypassing the check for object existence which is made when you use Model.save().

Just make whatever changes you want to your model instance and call update, passing your instance and the names of any fields to be updated.

Usage example:

import datetime

from forum.models import Topic
from forum.utils.models import update

topic = Topic.objects.get(pk=1)
topic.post_count += 1
topic.last_post_at = datetime.datetime.now()
update(topic, 'post_count', 'last_post_at')

(Originally intended as a comment on Snippet 479, but comments aren't working for me)

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.