Commits

Anonymous committed 26ce7cd

Fixed #7: Exclude unset primary keys from embedded model instances.

At the same time, simplified EmbeddedModelField.pre_save and .get_db_prep_save.

Comments (0)

Files changed (2)

djangotoolbox/fields.py

             raise TypeError("Expected instance of type %r, not %r" % (
                             type(model), type(embedded_instance)))
 
-        data = dict((field.name, field.pre_save(embedded_instance, add))
-                    for field in embedded_instance._meta.fields)
-        return embedded_instance, data
+        values = []
+        for field in embedded_instance._meta.fields:
+            value = field.pre_save(embedded_instance, add)
+            if field.primary_key and value == field.default:
+                # exclude unset pks ({"id" : None})
+                continue
+            values.append((field, value))
 
-    def get_db_prep_value(self, (embedded_instance, embedded_dict), **kwargs):
-        if embedded_dict is None:
+        return embedded_instance, values
+
+    def get_db_prep_value(self, (embedded_instance, value_list), **kwargs):
+        if value_list is None:
             return None
-        values = {}
-        for name, value in embedded_dict.iteritems():
-            field = embedded_instance._meta.get_field(name)
-            values[field.column] =  field.get_db_prep_value(value, **kwargs)
+        values = dict((field.column, field.get_db_prep_value(value, **kwargs))
+                      for field, value in value_list)
         if self.embedded_model is None:
             values.update({'_module' : embedded_instance.__class__.__module__,
                            '_model'  : embedded_instance.__class__.__name__})

djangotoolbox/tests.py

         self.assertIsInstance(instance.simple, EmbeddedModel)
         # Make sure get_prep_value is called:
         self.assertEqual(instance.simple.someint, 5)
-        # AutoFields' values should not be populated:
+        # Primary keys should not be populated...
         self.assertEqual(instance.simple.id, None)
+        # ... unless set explicitly.
+        instance.simple.id = instance.id
+        instance.save()
+        instance = EmbeddedModelFieldModel.objects.get()
+        self.assertEqual(instance.simple.id, instance.id)
 
     def test_pre_save(self):
         # Make sure field.pre_save is called
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.