calculate remaining import fields based on 2 import fields

Issue

I have a model with multiple fields. I want to make an importer (possibly with the django import-export library) that only takes two fields and with that calculates the rest of the fields that the model has.
I wanted to listen and ask if you know of ways to do this. Since the documentation does not mention much.

Thank you all!

Solution

You can use a custom resource for import mixin in model admin class

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

You can find more hooks like before_xxx or after_xxx at ModelResource source code, or see https://django-import-export.readthedocs.io/en/latest/api_resources.html#import_export.resources.Resource.after_save_instance

Answered By – Xianzhi Xia

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published