Skip to content

Commit

Permalink
fix(django): fix issue with uuid pk and auto_now_add
Browse files Browse the repository at this point in the history
  • Loading branch information
taylor-cedar committed Feb 11, 2022
1 parent d6bf014 commit 777c787
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion django_bulk_load/django.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def records_to_models(


def _default_model_to_value(model, field, connection):
field_val = field.pre_save(model, add=model.pk is None)
field_val = field.pre_save(model, add=model._state.adding)
return field.get_db_prep_save(field_val, connection=connection)


Expand Down
20 changes: 20 additions & 0 deletions tests/test_bulk_upsert_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .test_project.models import (
TestComplexModel,
TestForeignKeyModel,
TestUUIDModel
)


Expand Down Expand Up @@ -228,6 +229,25 @@ def test_upsert_return_models(self):
self.assertEqual(saved_model_1.id, post_model_1.id)
self.assertEqual(saved_model_3.id, post_model_3.id)

def test_upsert_and_return_models_uuid(self):
unsaved_model = TestUUIDModel()
saved_model = TestUUIDModel()
saved_model.save()
old_modified_on = saved_model.modified_on

pre_models = [unsaved_model, saved_model]
post_models = bulk_upsert_models(pre_models, return_models=True)

post_unsaved_model = [model for model in post_models if model.id == unsaved_model.id][0]
post_saved_model = [model for model in post_models if model.id == saved_model.id][0]

self.assertIsNotNone(post_unsaved_model.modified_on)
self.assertIsNotNone(post_unsaved_model.created_on)
self.assertIsNotNone(post_saved_model.created_on)
self.assertLess(old_modified_on, post_saved_model.modified_on)



def test_upsert_insert_only_fields(self):
saved_model_1 = TestComplexModel(integer_field=1, string_field="a")
saved_model_1.save()
Expand Down
8 changes: 8 additions & 0 deletions tests/test_project/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.db import models
from uuid import uuid4


class TestForeignKeyModel(models.Model):
Expand All @@ -13,3 +14,10 @@ class TestComplexModel(models.Model):
test_foreign = models.ForeignKey(
TestForeignKeyModel, on_delete=models.PROTECT, null=True
)



class TestUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now=True)

0 comments on commit 777c787

Please sign in to comment.