Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-import-export post_save called twice

I created a custom user subclassed from AbstractUser and a post_save signal and a receiver that prints the new user's id.

@receiver(post_save, sender=CustomUser, dispatch_uid='members.models.customuser.post_save')
def post_save_custom_user(sender, instance=None, created=False, **kwargs):         
    if not created:                                                                
        return                                                                     
    print('post_save_custom_user: {}'.format(instance.id))

When I create a new user via the admin interface the receiver is called once. When I import a user using django-import-export the receiver is called twice: once after the initial Submit of the import file and then again after the Confirm Import. Browsing through the code I see it creates the user in dry_run, rolls back the transaction and creates it again. But how can I tell in my receiver if it's a dry run or not?

I am using Python 3.6, Django 3.0.3, django-import-export 2.0.1

like image 731
Mike Avatar asked Feb 08 '20 06:02

Mike


Video Answer


1 Answers

It appears that django-import-export triggers the post_save on an import confirmation and then again after the import. Recommendations to use on_commit didn't work for me, hence I had to stop using the signals. There's ModelResource.after_save_instace method though:

class MyResource(ModelResource):

    class Meta:
        model = MyModel
    
    def after_save_instance(
        self, instance: MyModel, using_transactions: bool, dry_run: bool,
    ):
        super().after_save_instance(instance, using_transactions, dry_run)
        if dry_run is False:
            my_model_on_save_action(instance)
like image 134
Victor Avatar answered Sep 23 '22 01:09

Victor