Skip to content

Commit

Permalink
Merge pull request #321 from ericdwang/master
Browse files Browse the repository at this point in the history
Fix AttributeErrors when importing readonly fields from annotated values
  • Loading branch information
bmihelac committed Sep 28, 2015
2 parents da5fa9d + f6cd5d0 commit 74ef90b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ The following is a list of much appreciated contributors:
* AyumuKasuga (Andrey Kostakov)
* luto
* gallochri (Christian Galeffi)
* ericdwang (Eric Wang)
2 changes: 1 addition & 1 deletion import_export/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def get_value(self, obj):

for attr in attrs:
try:
value = getattr(value, attr)
value = getattr(value, attr, None)
except (ValueError, ObjectDoesNotExist):
# needs to have a primary key value before a many-to-many
# relationship can be used.
Expand Down
27 changes: 27 additions & 0 deletions tests/core/tests/resources_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from copy import deepcopy

from django.db import models
from django.db.models import Count
from django.db.models.fields import FieldDoesNotExist
from django.test import (
TestCase,
Expand Down Expand Up @@ -514,6 +515,32 @@ def field_from_django_field(self, field_name, django_field, readonly):
resource = B()
self.assertEqual({'sound': 'quack'}, B.fields['published'])

def test_readonly_annotated_field_import_and_export(self):
class B(BookResource):
total_categories = fields.Field('total_categories', readonly=True)

class Meta:
model = Book
skip_unchanged = True

cat1 = Category.objects.create(name='Cat 1')
self.book.categories.add(cat1)

resource = B()

# Verify that the annotated field is correctly exported
dataset = resource.export(
Book.objects.annotate(total_categories=Count('categories')))
self.assertEqual(int(dataset.dict[0]['total_categories']), 1)

# Verify that importing the annotated field raises no errors and that
# the rows are skipped
result = resource.import_data(dataset, raise_errors=True)
self.assertFalse(result.has_errors())
self.assertEqual(len(result.rows), len(dataset))
self.assertEqual(
result.rows[0].import_type, results.RowResult.IMPORT_TYPE_SKIP)


class ModelResourceTransactionTest(TransactionTestCase):

Expand Down

0 comments on commit 74ef90b

Please sign in to comment.