Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 25th, 2012  |  syntax: Python  |  size: 6.02 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. def save(self, force_insert=False, force_update=False, using=None):
  2.         """
  3.        Saves the current instance. Override this in a subclass if you want to
  4.        control the saving process.
  5.  
  6.        The 'force_insert' and 'force_update' parameters can be used to insist
  7.        that the "save" must be an SQL insert or update (or equivalent for
  8.        non-SQL backends), respectively. Normally, they should not be set.
  9.        """
  10.         if force_insert and force_update:
  11.             raise ValueError("Cannot force both insert and updating in model saving.")
  12.         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  13.  
  14.     save.alters_data = True
  15.  
  16.     def save_base(self, raw=False, cls=None, origin=None, force_insert=False,
  17.             force_update=False, using=None):
  18.         """
  19.        Does the heavy-lifting involved in saving. Subclasses shouldn't need to
  20.        override this method. It's separate from save() in order to hide the
  21.        need for overrides of save() to pass around internal-only parameters
  22.        ('raw', 'cls', and 'origin').
  23.        """
  24.         using = using or router.db_for_write(self.__class__, instance=self)
  25.         connection = connections[using]
  26.         assert not (force_insert and force_update)
  27.         if cls is None:
  28.             cls = self.__class__
  29.             meta = cls._meta
  30.             if not meta.proxy:
  31.                 origin = cls
  32.         else:
  33.             meta = cls._meta
  34.  
  35.         if origin and not meta.auto_created:
  36.             signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using)
  37.  
  38.         # If we are in a raw save, save the object exactly as presented.
  39.         # That means that we don't try to be smart about saving attributes
  40.         # that might have come from the parent class - we just save the
  41.         # attributes we have been given to the class we have been given.
  42.         # We also go through this process to defer the save of proxy objects
  43.         # to their actual underlying model.
  44.         if not raw or meta.proxy:
  45.             if meta.proxy:
  46.                 org = cls
  47.             else:
  48.                 org = None
  49.             for parent, field in meta.parents.items():
  50.                 # At this point, parent's primary key field may be unknown
  51.                 # (for example, from administration form which doesn't fill
  52.                 # this field). If so, fill it.
  53.                 if field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None:
  54.                     setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
  55.  
  56.                 self.save_base(cls=parent, origin=org, using=using)
  57.  
  58.                 if field:
  59.                     setattr(self, field.attname, self._get_pk_val(parent._meta))
  60.             if meta.proxy:
  61.                 return
  62.  
  63.         if not meta.proxy:
  64.             non_pks = [f for f in meta.local_fields if not f.primary_key]
  65.  
  66.             # First, try an UPDATE. If that doesn't update anything, do an INSERT.
  67.             pk_val = self._get_pk_val(meta)
  68.             pk_set = pk_val is not None
  69.             record_exists = True
  70.             manager = cls._base_manager
  71.             if pk_set:
  72.                 # Determine whether a record with the primary key already exists.
  73.                 if (force_update or (not force_insert and
  74.                         manager.using(using).filter(pk=pk_val).exists())):
  75.                     # It does already exist, so do an UPDATE.
  76.                     if force_update or non_pks:
  77.                         values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
  78.                         rows = manager.using(using).filter(pk=pk_val)._update(values)
  79.                         if force_update and not rows:
  80.                             raise DatabaseError("Forced update did not affect any rows.")
  81.                 else:
  82.                     record_exists = False
  83.             if not pk_set or not record_exists:
  84.                 if meta.order_with_respect_to:
  85.                     # If this is a model with an order_with_respect_to
  86.                     # autopopulate the _order field
  87.                     field = meta.order_with_respect_to
  88.                     order_value = manager.using(using).filter(**{field.name: getattr(self, field.attname)}).count()
  89.                     self._order = order_value
  90.  
  91.                 if not pk_set:
  92.                     if force_update:
  93.                         raise ValueError("Cannot force an update in save() with no primary key.")
  94.                     values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True), connection=connection))
  95.                         for f in meta.local_fields if not isinstance(f, AutoField)]
  96.                 else:
  97.                     values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True), connection=connection))
  98.                         for f in meta.local_fields]
  99.  
  100.                 record_exists = False
  101.  
  102.                 update_pk = bool(meta.has_auto_field and not pk_set)
  103.                 if values:
  104.                     # Create a new record.
  105.                     result = manager._insert(values, return_id=update_pk, using=using)
  106.                 else:
  107.                     # Create a new record with defaults for everything.
  108.                     result = manager._insert([(meta.pk, connection.ops.pk_default_value())], return_id=update_pk, raw_values=True, using=using)
  109.  
  110.                 if update_pk:
  111.                     setattr(self, meta.pk.attname, result)
  112.             transaction.commit_unless_managed(using=using)
  113.  
  114.         # Store the database on which the object was saved
  115.         self._state.db = using
  116.         # Once saved, this is no longer a to-be-added instance.
  117.         self._state.adding = False
  118.  
  119.         # Signal that the save is complete
  120.         if origin and not meta.auto_created:
  121.             signals.post_save.send(sender=origin, instance=self,
  122.                 created=(not record_exists), raw=raw, using=using)