Skip to content

Commit

Permalink
Prevent error comparing m2m field of the new objects (#1560)
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosal0ns0 committed Mar 10, 2023
1 parent 4ac05ae commit b477f24
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,4 @@ The following is a list of much appreciated contributors:
* Ptosiek (Antonin)
* samupl (Jakub Szafrański)
* smunoz-ml (Santiago Muñoz)
* carlosal0ns0 (Carlos Alonso)
2 changes: 1 addition & 1 deletion import_export/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ def skip_row(self, instance, original, row, import_validation_errors=None):
# m2m instance values are taken from the 'row' because they
# have not been written to the 'instance' at this point
instance_values = list(field.clean(row))
original_values = list(field.get_value(original).all())
original_values = list() if original.pk is None else list(field.get_value(original).all())
if len(instance_values) != len(original_values):
return False

Expand Down
15 changes: 15 additions & 0 deletions tests/core/tests/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -1740,6 +1740,21 @@ def test_many_to_many_widget_create(self):
self.assertEqual(result.rows[0].import_type, results.RowResult.IMPORT_TYPE_UPDATE)
self.assertEqual(Category.objects.first(), book.categories.first())

def test_many_to_many_widget_create_with_m2m_being_compared(self):
# issue 1558 - when the object is a new instance and m2m is evaluated for differences
dataset_headers = ["categories"]
dataset_row = ["1"]
dataset = tablib.Dataset(headers=dataset_headers)
dataset.append(dataset_row)
book_resource = BookResource()
book_resource._meta.skip_unchanged = True

result = book_resource.import_data(dataset, dry_run=False)

self.assertFalse(result.has_errors())
self.assertEqual(len(result.rows), 1)
self.assertEqual(result.rows[0].import_type, results.RowResult.IMPORT_TYPE_NEW)

def test_many_to_many_widget_update(self):
# the book is associated with 1 category ('Category 2')
# when we import a book with category 1, the book
Expand Down

0 comments on commit b477f24

Please sign in to comment.