Ticket #16649: save_no_select.diff

File save_no_select.diff, 2.5 KB (added by Anssi Kääriäinen, 13 years ago)

save() without select

  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    index 71fd1f7..b01bb0e 100644
    a b class Model(object):  
    515515        if not meta.proxy:
    516516            non_pks = [f for f in meta.local_fields if not f.primary_key]
    517517
    518             # First, try an UPDATE. If that doesn't update anything, do an INSERT.
    519518            pk_val = self._get_pk_val(meta)
    520519            pk_set = pk_val is not None
    521             record_exists = True
     520            record_exists = False
    522521            manager = cls._base_manager
    523             if pk_set:
    524                 # Determine whether a record with the primary key already exists.
    525                 if (force_update or (not force_insert and
    526                         manager.using(using).filter(pk=pk_val).exists())):
    527                     # It does already exist, so do an UPDATE.
    528                     if force_update or non_pks:
    529                         values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
    530                         rows = manager.using(using).filter(pk=pk_val)._update(values)
    531                         if force_update and not rows:
    532                             raise DatabaseError("Forced update did not affect any rows.")
    533                 else:
    534                     record_exists = False
     522            if pk_set and not force_insert:
     523                # Try to update the object. If something is updated, we know the record
     524                # existed. If not, we know it did not exists.
     525                if force_update or non_pks:
     526                    values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
     527                    rows = manager.using(using).filter(pk=pk_val)._update(values)
     528                    if rows:
     529                        record_exists = True
     530                    if not rows and force_update:
     531                        raise DatabaseError("Forced update did not affect any rows.")
     532                       
     533                elif not non_pks:
     534                    # There are no other fields than the pk in the model. In this case we do
     535                    # not check the existense by update
     536                    if manager.using(using).filter(pk=pk_val).exists():
     537                        record_exists = True
    535538            if not pk_set or not record_exists:
    536539                if meta.order_with_respect_to:
    537540                    # If this is a model with an order_with_respect_to
Back to Top