DJANGO пользовательский импорт CSV
У меня есть модель с несколькими полями. Я хочу сделать импортер (возможно, с помощью библиотеки django import-export), который принимает только два поля и с помощью этого вычисляет остальные поля, которые есть у модели. Я хотел послушать и спросить, знаете ли вы способы сделать это. Так как в документации мало что упоминается.
Спасибо всем!
Вы можете использовать пользовательский ресурс для импорта миксина в классе администрирования модели
class YourModelAdmin(ImportMixin, admin.ModelAdmin):
resource_class = YourModelCustomResource # 指定ImportMixin的resource_class
class YourModelCustomResource(resources.ModelResource):
def before_save_instance(self, instance, using_transactions, dry_run):
"""
Override to add additional logic. Does nothing by default.
"""
# TODO: calculates the rest of the fields
# The instance is instance of YourModelClass
# instance.field = ...
class Meta:
model = YourModelClass
fields = ("field1", "field1") # fields you want to import
Вы можете найти больше крючков, таких как before_xxx или after_xxx в исходном коде ModelResource, или посмотреть https://django-import-export.readthedocs.io/en/latest/api_resources.html#import_export.resources.Resource.after_save_instance
Вы можете использовать пользовательский ресурс для импорта миксина в классе администрирования модели
class YourModelAdmin(ImportMixin, admin.ModelAdmin):
resource_class = YourModelCustomResource # 指定ImportMixin的resource_class
class YourModelCustomResource(resources.ModelResource):
def before_save_instance(self, instance, using_transactions, dry_run):
"""
Override to add additional logic. Does nothing by default.
"""
# TODO: calculates the rest of the fields
# The instance is instance of YourModelClass
# instance.field = ...
class Meta:
model = YourModelClass
fields = ("field1", "field1") # fields you want to import
Вы можете найти больше крючков, таких как before_xxx или after_xxx в исходном коде ModelResource, или посмотреть https://django-import-export.readthedocs.io/en/latest/api_resources.html#import_export.resources.Resource.after_save_instance