'calculate remaining import fields based on 2 import fields

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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xianzhi Xia