Code

Ticket #16649: save_no_select.diff

File save_no_select.diff, 2.5 KB (added by akaariai, 3 years ago)

save() without select

Line 
1diff --git a/django/db/models/base.py b/django/db/models/base.py
2index 71fd1f7..b01bb0e 100644
3--- a/django/db/models/base.py
4+++ b/django/db/models/base.py
5@@ -515,23 +515,26 @@ class Model(object):
6         if not meta.proxy:
7             non_pks = [f for f in meta.local_fields if not f.primary_key]
8 
9-            # First, try an UPDATE. If that doesn't update anything, do an INSERT.
10             pk_val = self._get_pk_val(meta)
11             pk_set = pk_val is not None
12-            record_exists = True
13+            record_exists = False
14             manager = cls._base_manager
15-            if pk_set:
16-                # Determine whether a record with the primary key already exists.
17-                if (force_update or (not force_insert and
18-                        manager.using(using).filter(pk=pk_val).exists())):
19-                    # It does already exist, so do an UPDATE.
20-                    if force_update or non_pks:
21-                        values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
22-                        rows = manager.using(using).filter(pk=pk_val)._update(values)
23-                        if force_update and not rows:
24-                            raise DatabaseError("Forced update did not affect any rows.")
25-                else:
26-                    record_exists = False
27+            if pk_set and not force_insert:
28+                # Try to update the object. If something is updated, we know the record
29+                # existed. If not, we know it did not exists.
30+                if force_update or non_pks:
31+                    values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
32+                    rows = manager.using(using).filter(pk=pk_val)._update(values)
33+                    if rows:
34+                        record_exists = True
35+                    if not rows and force_update:
36+                        raise DatabaseError("Forced update did not affect any rows.")
37+                       
38+                elif not non_pks:
39+                    # There are no other fields than the pk in the model. In this case we do
40+                    # not check the existense by update
41+                    if manager.using(using).filter(pk=pk_val).exists():
42+                        record_exists = True
43             if not pk_set or not record_exists:
44                 if meta.order_with_respect_to:
45                     # If this is a model with an order_with_respect_to