我需要以某种方式将用户信息ForeignKeyWidget从资源类传递到类,我在其中创建foreignKey对象:
class CompanyWidget(ForeignKeyWidget):
def clean(self, value, row=None, *args, **kwargs):
print(self.user, file=sys.stderr)
if not value:
return None
else:
obj, _ = Company.objects.get_or_create(
name=value,
created_by='I NEED USER INFORMATION HERE SOMEHOW',
)
return obj
做这个的最好方式是什么?
我尝试自己解决这个问题,并且非常接近,但无法解决最后一块难题。您覆盖__init__ 资源中的类并在那里获取用户信息。然后,我不知道如何将这些self.user信息传递到类变量中company。
这是代码:
class 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',
attribute='company',
widget=CompanyWidget(model=Company, field='name', user='I NEED TO PASS USER HERE FROM __INIT__'))
def after_import_instance(self, instance, new, **kwargs):
instance.created_by = kwargs['user']
如果我以某种方式设法将用户信息传递到变量中**kwargs,company那么我可以通过覆盖ForeignKeyWidget的__init__类来在下游使用它:
class CompanyWidget(ForeignKeyWidget):
def __init__(self, model, field='pk', *args, **kwargs):
self.model = model
self.field = field
self.user = kwargs.pop('user', None)
super(CompanyWidget, self).__init__(model, *args, **kwargs)
def clean(self, value, row=None, *args, **kwargs):
print(self.user, file=sys.stderr)
if not value:
return None
else:
obj, _ = Company.objects.get_or_create(
name=value,
created_by=self.user,
)
return obj
任何帮助将不胜感激,我花了很长时间才到达这里,我觉得我真的很接近。先感谢您。
牧羊人nacy
相关分类