django-import-export:实例数据在保存后种族条件未更新

问题描述

我有一个允许通过django-import-export导入的模型。

在导入Event实例后,我需要创建相关对象,因此我将使用after_save_instance来启动芹菜任务,该任务通过ID引用对象。但是在这些任务中,当我使用从Resource类传递的ID从数据库中检索对象时,我会得到旧数据。

例如,导入的数据会更改现有date对象上的Event值,并且在after_save_instance期间会更新数据,但是一旦celery任务检索到数据,它就会有所不同。 / p>

这是精简的资源类;

class EventImportResource(resources.ModelResource):
    """ Admin importer for Events """
    date = fields.Field(
        attribute='date',column_name='date',widget=LocalisedDateWidget(
            format=get_format('UK_DATE_INPUT_FORMATS')
        )
    )

    class Meta:
        model = Event

        fields = [
            'id','date','name','city','state','country','url'
        ]

    def after_save_instance(self,instance,using_transactions,dry_run):
        """
        Override to add additional logic. Does nothing by default.
        """
        if not dry_run:
            transaction.on_commit(lambda: create_categories.delay(instance.id))


            # debugging at this point shows the new value
            # >>> instance.date
            # webapp_1           | datetime.date(2020,10,25)

在celery任务中,我需要从数据库获取对象并执行其他一些对象创建等操作。这时,实例上的属性after_save_instance中的实例不同。

@celery_app.task
def create_categories(event_id):
    """
    Create Category objects for an event

    :param event_id: Event ID
    :return:
    """
    time.sleep(30)  # Doesn't seem to help
    categories = []
    instance = Event.objects.get(id=event_id)
    instance.refresh_from_db()  # Tried this to resolve the issue,but didn't help

    # debugging at this point shows the old value
    # >>> instance.date
    # webapp_1           | datetime.datetime(2020,24,23,tzinfo=<UTC>)

在保存实例(docs)之后将调用resource方法,因此这只能是由于在提交事务之前拾取了celery任务引起的竞争条件。尽管有尝试等待on_commit()sleep的芹菜来接班的情况。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)