1 回答
TA贡献1862条经验 获得超7个赞
事实证明,完全不使用ForeignKeyWidget 来实现这一点更容易。如果您有多个不唯一但具有相同名称的外键(在我的例子中,由不同用户创建相同的公司名称),则可以通过以下方式解决问题:
类 ContactResource(resources.ModelResource):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(ContactResource, self).__init__(*args, **kwargs)
company = fields.Field(column_name='company')
class Meta:
model = Contact
skip_unchanged = True
report_skipped = True
exclude =('is_active', 'created_by')
export_order = ('id','first_name','last_name','email','phone','address','description','company','created_on','website','job_title','birthday')
def after_import_instance(self, instance, new, **kwargs):
instance.created_by = self.user # kwargs['user']
def import_field(self, field, obj, data):
field_name = self.get_field_name(field)
method = getattr(self, 'clean_%s' % field_name, None)
if method is not None:
obj = method(field, obj, data)
super(ContactResource, self).import_field(field, obj, data)
def clean_company(self, field, obj, data):
name = data[field.column_name]
company, created = Company.objects.get_or_create(name=name, created_by=self.user)
obj.company = company
return obj
添加回答
举报