Django-import-export before_import_row如果不存在则自动创建对象

时间:2018-04-12 15:21:48

标签: python django excel django-import-export

我在使用Django-import-export时面临当前问题:

在我的admin.py中:

class QuestionResource(resources.ModelResource):
category = fields.Field(
        column_name='category',
        attribute='category',
        widget=ForeignKeyWidget(Category, 'category')
    )

class Meta:
    model = Question
    fields = ['id', 'question', 'category', 'answer',]
    # exclude = ('created', 'modified', 'verified', 'count', 'user_created')

# PREVIOUS THINGS I TRIED: 

# def _post_import(model, **kwargs):
#   query = self.fields['category']
#   category = Question.objects.get_or_create(category=query)
#   return category

# def before_import(self, dataset, dry_run, *args, **kwargs):
#   query = self.fields['category']
#   for q in query:
#       Category.objects.get_or_create(category=q)

# def before_import_row(row, *args, **kwargs):
#   category = self.fields['category']
#   Category.objects.get_or_create(category=category)

def before_import_row(row, *args, **kwargs):
    category = row.fields['category']
    Category.objects.get_or_create(category=category)

正如您所看到的,我添加了之前作为评论尝试的内容。我收到的错误是:

Errors

Line number: 5 - Category matching query does not exist.
Pokemon, 9526, Is er een voorvak?, Ja, bij de Alpha is een voorvak.

Traceback (most recent call last):
File "/Users/iam-tony/.envs/lib/python3.6/site-packages/import_export/resources.py", line 457, in import_row
self.import_obj(instance, row, dry_run)
File "/Users/iam-tony/.envs/lib/python3.6/site-packages/import_export/resources.py", line 329, in import_obj
self.import_field(field, obj, data)
File "/Users/iam-tony/.envs/lib/python3.6/site-packages/import_export/resources.py", line 316, in import_field
field.save(obj, data, is_m2m)
File "/Users/iam-tony/.envs/lib/python3.6/site-packages/import_export/fields.py", line 115, in save
cleaned = self.clean(data)
File "/Users/iam-tony/.envs/lib/python3.6/site-packages/import_export/fields.py", line 69, in clean
value = self.widget.clean(value, row=data)
File "/Users/iam-tony/.envs/lib/python3.6/site-packages/import_export/widgets.py", line 334, in clean
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val})
File "/Users/iam-tony/.envs/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get
self.model._meta.object_name
questions.models.DoesNotExist: Category matching query does not exist.

我错过了什么?我似乎无法找到关于此的任何文档(或者有但我不理解)

提前致谢!

1 个答案:

答案 0 :(得分:0)

什么是Category#category字段?类别的名称?字符串吗?

尝试将该字段重置为创建的类别的主键:

def before_import_row(self, row, **kwargs):
    name = row.get('category')
    (cat, _created) = Category.objects.get_or_create(name=name)
    row['category'] = cat.id