Skip to content

Commit

Permalink
Merge pull request #89 from prajnamort/notsaved_pk_issue
Browse files Browse the repository at this point in the history
Notsaved pk issue. Definitely fixes #88.
Thanks @prajnamort !
  • Loading branch information
romgar committed Nov 9, 2016
2 parents 4d9d511 + 878c8bb commit 998f274
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/dirtyfields/dirtyfields.py
Expand Up @@ -82,10 +82,11 @@ def _as_dict_m2m(self):
return {}

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
if not self.pk:
if self._state.adding:
# If the object has not yet been saved in the database, all fields are considered dirty
# for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
initial_dict = self._as_dict(check_relationship, include_primary_key=False)
pk_specified = self.pk is not None
initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
return initial_dict

if check_m2m is not None and not self.ENABLE_M2M_CHECK:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_core.py
Expand Up @@ -49,6 +49,19 @@ def test_dirty_fields():
}


@pytest.mark.django_db
def test_dirty_fields_for_notsaved_pk():
tm = TestModel(id=1)

# Initial state is dirty, so should return all fields
assert tm.get_dirty_fields() == {'id': 1, 'boolean': True, 'characters': ''}

tm.save()

# Saving them make them not dirty anymore
assert tm.get_dirty_fields() == {}


@pytest.mark.django_db
def test_relationship_option_for_foreign_key():
tm1 = TestModel.objects.create()
Expand Down

0 comments on commit 998f274

Please sign in to comment.