我尝试关注:https ://github.com/bmihelac/django-import-export/blob/master/docs/getting_started.rst
我将资源定义如下:
from import_export import resources
from core_backend.models.exhibitor import Exhibitor
from django.contrib.auth.models import User
from import_export import fields
class ExhibitorResource(resources.ModelResource):
email = fields.Field()
class Meta:
model = Exhibitor
fields = ('id', 'stand_id', 'email', 'title')
def dehydrate_email(self, exhibitor):
email = User.objects.filter(id=exhibitor.user_id)[0].email
return email
然后在shell中我尝试:
import tablib
from import_export import resources
from core_backend.models.exhibitor import Exhibitor
from core_backend.models.exhibitor_resource import ExhibitorResource
my_res = ExhibitorResource()
my_res.fields
#{'email': <import_export.fields.Field: email>, u'id': <import_export.fields.Field: id>, 'title': <import_export.fields.Field: title>, 'stand_id': <import_export.fields.Field: stand_id>}
dataset = tablib.Dataset(['', '2', 'w@x.pl', 'fooo'],
headers=['id', 'stand_id', 'email', 'title'])
res = my_res.import_data(dataset, dry_run=True)
res.has_errors()
True
是什么原因?has_errors()
是针对 Resource 还是整个模型进行验证?
我的资源定义是:
a) 模型字段的子集Exhibitor
email
b)添加了不在Exhibitor
类中的额外字段
更新:
我跑raise_errors=True
res = my_res.import_data(dataset, dry_run=True,raise_errors=True)
它打印:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/import_export/resources.py", line 350, in import_data
six.reraise(*sys.exc_info())
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/import_export/resources.py", line 335, in import_data
self.import_obj(instance, row, real_dry_run)
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/import_export/resources.py", line 201, in import_obj
self.import_field(field, obj, data)
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/import_export/resources.py", line 193, in import_field
field.save(obj, data)
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/import_export/fields.py", line 83, in save
setattr(obj, self.attribute, self.clean(data))
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/import_export/fields.py", line 51, in clean
value = self.widget.clean(value)
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/import_export/widgets.py", line 137, in clean
return self.model.objects.get(pk=pk) if pk else None
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "/Users/andi/.virtualenvs/daftdjango/lib/python2.7/site-packages/django/db/models/query.py", line 307, in get
self.model._meta.object_name)
DoesNotExist: Stand matching query does not exist.