首页 > 解决方案 > Concurency celery django 批量创建或更新

问题描述

我有一个 django 的竞争问题,我有一个更新表中用户数量的 celery 任务。由于要更新的​​行很多,我使用批量更新,为了避免创建不必要的行,我使用批量创建。

all_statistic_user = StatisticsCountriesUser.objects.filter(user__in=all_branch_user,countries=user.country)
if all_statistic_user:
    all_statistic_user.update(total_users=F('total_users') +1)

all_statistic_user = StatisticsCountriesUser.objects.exclude(user__in=all_branch_user,countries=user.country)
if all_statistic_user:
    all_statistic_user = [StatisticsCountriesUser(user_id=user.id,countries=user.country) for user in all_statistic_user ]
    StatisticsCountriesUser.objects.bulk_create(all_statistic_user)
else:
    all_statistic_user = [StatisticsCountriesUser(user_id=user.id, countries=user.country) for user in all_branch_user]
    StatisticsCountriesUser.objects.bulk_create(all_statistic_user)

问题是如果任务是异步执行的,如果任务同时执行第一个任务创建用户列表,那么第二个任务也检索用户列表,第一个创建或更新用户,但是第二个任务该列表不再具有更新或创建的正确信息。我认为的解决方案是将任务放在同步列表中而不是异步的,这可能吗?先感谢您

标签: djangopython-3.xconcurrencycelery

解决方案


推荐阅读