Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Refactored the way save() works so that non-integer primary keys are …

…now possible. custom_pk unit tests (from [458]) now pass. Refs #81.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@462 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 4622e0ff82f82be424439cc218182a4f18c3e17c 1 parent 63e1f3d
Adrian Holovaty authored August 10, 2005
60  django/core/meta/__init__.py
@@ -208,6 +208,14 @@ def __init__(self, module_name='', verbose_name='', verbose_name_plural='', db_t
208 208
         if self.pk is None:
209 209
             self.fields.insert(0, AutoField('id', 'ID', primary_key=True))
210 210
             self.pk = self.fields[0]
  211
+        # Cache whether this has an AutoField.
  212
+        self.has_auto_field = False
  213
+        for f in self.fields:
  214
+            is_auto = isinstance(f, AutoField)
  215
+            if is_auto and self.has_auto_field:
  216
+                raise AssertionError, "A model can't have more than one AutoField."
  217
+            elif is_auto:
  218
+                self.has_auto_field = True
211 219
 
212 220
     def __repr__(self):
213 221
         return '<Options for %s>' % self.module_name
@@ -717,37 +725,27 @@ def method_save(opts, self):
717 725
         self._pre_save()
718 726
     non_pks = [f for f in opts.fields if not f.primary_key]
719 727
     cursor = db.db.cursor()
720  
-    add = not bool(getattr(self, opts.pk.name))
721  
-    for f in non_pks:
722  
-        f.pre_save(self, getattr(self, f.name), add)
723  
-    db_values = [f.get_db_prep_save(getattr(self, f.name)) for f in non_pks]
724  
-    # OneToOne objects are a special case because there's no AutoField, and the
725  
-    # primary key field is set manually.
726  
-    if isinstance(opts.pk.rel, OneToOne):
727  
-        cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \
728  
-            (opts.db_table, ','.join(['%s=%%s' % f.name for f in non_pks]),
729  
-            opts.pk.name), db_values + [getattr(self, opts.pk.name)])
730  
-        if cursor.rowcount == 0: # If nothing was updated, add the record.
731  
-            field_names = [f.name for f in opts.fields]
732  
-            placeholders = ['%s'] * len(field_names)
733  
-            cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \
734  
-                (opts.db_table, ','.join(field_names), ','.join(placeholders)),
735  
-                [f.get_db_prep_save(getattr(self, f.name)) for f in opts.fields])
736  
-    else:
737  
-        if not add:
738  
-            cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \
739  
-                (opts.db_table, ','.join(['%s=%%s' % f.name for f in non_pks]),
740  
-                opts.pk.name), db_values + [getattr(self, opts.pk.name)])
741  
-        else:
742  
-            field_names = [f.name for f in non_pks]
743  
-            placeholders = ['%s'] * len(field_names)
744  
-            if opts.order_with_respect_to:
745  
-                field_names.append('_order')
746  
-                placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \
747  
-                    (opts.db_table, opts.order_with_respect_to.name))
748  
-                db_values.append(getattr(self, opts.order_with_respect_to.name))
749  
-            cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \
750  
-                (opts.db_table, ','.join(field_names), ','.join(placeholders)), db_values)
  728
+
  729
+    # First, try an UPDATE. If that doesn't update anything, do an INSERT.
  730
+    pk_set = bool(getattr(self, opts.pk.name))
  731
+    if pk_set:
  732
+        db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.name), False)) for f in non_pks]
  733
+        cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % (opts.db_table,
  734
+            ','.join(['%s=%%s' % f.name for f in non_pks]), opts.pk.name),
  735
+            db_values + [getattr(self, opts.pk.name)])
  736
+    if not pk_set or cursor.rowcount == 0:
  737
+        field_names = [f.name for f in opts.fields if not isinstance(f, AutoField)]
  738
+        placeholders = ['%s'] * len(field_names)
  739
+        db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.name), True)) for f in opts.fields if not isinstance(f, AutoField)]
  740
+        if opts.order_with_respect_to:
  741
+            field_names.append('_order')
  742
+            # TODO: This assumes the database supports subqueries.
  743
+            placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \
  744
+                (opts.db_table, opts.order_with_respect_to.name))
  745
+            db_values.append(getattr(self, opts.order_with_respect_to.name))
  746
+        cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % (opts.db_table,
  747
+            ','.join(field_names), ','.join(placeholders)), db_values)
  748
+        if opts.has_auto_field:
751 749
             setattr(self, opts.pk.name, db.get_last_insert_id(cursor, opts.db_table, opts.pk.name))
752 750
     db.db.commit()
753 751
     # Run any post-save hooks.
23  django/core/meta/fields.py
@@ -82,12 +82,9 @@ def __init__(self, name, verbose_name=None, primary_key=False,
82 82
         else:
83 83
             self.db_index = db_index
84 84
 
85  
-    def pre_save(self, obj, value, add):
86  
-        """
87  
-        Hook for altering the object obj based on the value of this field and
88  
-        and on the add/change status.
89  
-        """
90  
-        pass
  85
+    def pre_save(self, value, add):
  86
+        "Returns field's value just before saving."
  87
+        return value
91 88
 
92 89
     def get_db_prep_save(self, value):
93 90
         "Returns field's value prepared for saving into a database."
@@ -236,6 +233,10 @@ def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
236 233
 
237 234
 class AutoField(Field):
238 235
     empty_strings_allowed = False
  236
+    def __init__(self, *args, **kwargs):
  237
+        assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__
  238
+        Field.__init__(self, *args, **kwargs)
  239
+
239 240
     def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False):
240 241
         if not rel:
241 242
             return [] # Don't add a FormField unless it's in a related context.
@@ -280,9 +281,10 @@ def get_db_prep_lookup(self, lookup_type, value):
280 281
             value = str(value)
281 282
         return Field.get_db_prep_lookup(self, lookup_type, value)
282 283
 
283  
-    def pre_save(self, obj, value, add):
  284
+    def pre_save(self, value, add):
284 285
         if self.auto_now or (self.auto_now_add and add):
285  
-            setattr(obj, self.name, datetime.datetime.now())
  286
+            return datetime.datetime.now()
  287
+        return value
286 288
 
287 289
     def get_db_prep_save(self, value):
288 290
         # Casts dates into string format for entry into database.
@@ -483,9 +485,10 @@ def get_db_prep_lookup(self, lookup_type, value):
483 485
             value = str(value)
484 486
         return Field.get_db_prep_lookup(self, lookup_type, value)
485 487
 
486  
-    def pre_save(self, obj, value, add):
  488
+    def pre_save(self, value, add):
487 489
         if self.auto_now or (self.auto_now_add and add):
488  
-            setattr(obj, self.name, datetime.datetime.now().time())
  490
+            return datetime.datetime.now().time()
  491
+        return value
489 492
 
490 493
     def get_db_prep_save(self, value):
491 494
         # Casts dates into string format for entry into database.

0 notes on commit 4622e0f

Please sign in to comment.
Something went wrong with that request. Please try again.