如何在Django芹菜中传递查询集

问题描述 投票:0回答:2

我正在尝试使用django构建Instagram机器人。我想实现django celery在后台运行任务。在这里,我面临一些问题。

task.py

from celery import shared_task
from projects.services.instagram_bot import InstagramBot


@shared_task
def lazy_post_link_1_task(post_url, current_user, bot_id, email, password, time_interval, comments):
    instagram_bot = InstagramBot()
    instagram_bot.comment_on_post(post_url, current_user, bot_id, email, password, time_interval, comments)

views.py

for bot in lazy_bots:
    lazy_bot_filter_comments = Comments.objects.all().exclude(botscomment__bot_id=bot.id)[
                                                   :int(no_of_comment_for_lazy_bot)]

    lazy_post_link_1_task.delay(lazy_post_link_1, request.user, bot.id, bot.email, bot.password,
                                                    lazy_bot_time_interval,
                                                    lazy_bot_filter_comments)

我面临类似这样的错误enter image description here

我不知道我要执行的任务

django django-celery
2个回答
0
投票

您不能将查询集直接传递给Celery任务,因为任务参数必须可序列化。相反,您可以将对象ID的列表传递给任务,然后运行查询从任务本身。另一个可能的选择-如果您只需要数据并准备使用映射处理它,则使用Django serializer或更好的DRF serializers


0
投票

最佳实践是不要将模型实例/查询集传递给Celery。传递ID和其他信息来代替在工作者端建立此查询。

请勿将Django模型对象传递给Celery任务。为避免模型对象在传递给Celery任务之前已经更改的情况,请将对象的主键传递给Celery。然后,您当然必须在处理数据库之前使用主键从数据库中获取对象。

https://realpython.com/asynchronous-tasks-with-django-and-celery/

© www.soinside.com 2019 - 2024. All rights reserved.