Search code examples
djangodjango-import-export

Django import adding Many-to-Many relationship based on value non-model field


I'm using django-import-export to import an xls.

In the xls is a boolean field is_senior which is not a model field.

In the model I have a Many-to-Many relationship to a Model Level which has junior, senior etc.

If is_senior is True I want to:

senior = Level.objects.filter(name__icontains = 'senior').first()
instance.level.add(senior)

But the problem is: before_import_row knows the non-model field, but can't add m2m relationships after_save_instance doesn't have the non-model field

any ideas?


Solution

  • You can set temporary attributes on the Resource instance:

        def before_import_row(self, row, row_number=None, **kwargs):
            self.is_senior = row.get("is_senior")
    
    
        def after_save_instance(self, instance, using_transactions, dry_run):
            print(self.is_senior)
    

    This will work as long as rows, are not skipped for any reason (skip_row() is defined or in case of errors). Test thoroughly to ensure that is_senior is set correctly.