我发现最好的方法是使用自定义小部件。我在这里的 django-import-export GitHub 项目上找到了一个线程,其中包含很多有用的信息。由此我将这两个支持创建新对象的自定义小部件拼凑在一起。admin.py
通过将它们添加到您的模块中,它们都应该按原样工作:
from import_export.widgets import ManyToManyWidget
from django.db.models import QuerySet
class ForeignKeyWidgetWithCreation(ForeignKeyWidget):
"""
Taken from a GitHub post.
https://github.com/django-import-export/django-import-export/issues/318#issuecomment-139989178
"""
def __init__(self, model, field="pk", create=False, **kwargs):
self.model = model
self.field = field
self.create = create
super(ForeignKeyWidgetWithCreation, self).__init__(model, field=field, **kwargs)
def clean(self, value, **kwargs):
if not value:
return None
if self.create:
self.model.objects.get_or_create(**{self.field: value})
val = super(ForeignKeyWidgetWithCreation, self).clean(value, **kwargs)
return self.model.objects.get(**{self.field: val}) if val else None
class ManyToManyWidgetWithCreation(ManyToManyWidget):
"""
Taken from a GitHub post.
https://github.com/django-import-export/django-import-export/issues/318#issuecomment-139989178
"""
def __init__(self, model, field="pk", create=False, **kwargs):
self.model = model
self.field = field
self.create = create
super(ManyToManyWidgetWithCreation, self).__init__(model, field=field, **kwargs)
def clean(self, value, **kwargs):
# If no value was passed then we don't have anything to clean.
if not value:
return self.model.objects.none()
# Call the super method. This will return a QuerySet containing any pre-existing objects.
# Any missing objects will be
cleaned_value: QuerySet = super(ManyToManyWidgetWithCreation, self).clean(
value, **kwargs
)
# Value will be a string that is separated by `self.separator`.
# Each entry in the list will be a reference to an object. If the object exists it will
# appear in the cleaned_value results. If the number of objects in the cleaned_value
# results matches the number of objects in the delimited list then all objects already
# exist and we can just return those results.
object_list = value.split(self.separator)
if len(cleaned_value.all()) == len(object_list):
return cleaned_value
# If we are creating new objects then loop over each object in the list and
# use get_or_create to, um, get or create the object.
if self.create:
for object_value in object_list:
_instance, _new = self.model.objects.get_or_create(
**{self.field: object_value}
)
# Use `filter` to re-locate all the objects in the list.
model_objects = self.model.objects.filter(**{f"{self.field}__in": object_list})
return model_objects
您可以在您的导入导出模型资源类中使用它们,如下所示:
class SomeModelResource(Resource):
my_fk_field = fields.Field(
attribute='my_fk_field',
widget=ForeignKeyWidgetWithCreation(
model=models.OtherModel,
field='name',
create=True))
my_m2m_field = fields.Field(
attribute="my_m2m_field",
widget=ManyToManyWidgetWithCreation(
model=models.OtherM2MModel,
field="name",
separator="|",
create=True,
),
default="",
)