Skip to main content
 首页 » 编程设计

python之如何将 Django 对象发送到 celery 任务

2024年08月16日26insus

大家好!

在我提出问题之前,我尝试了这些 SO 帖子:

它们都不起作用!

我想让用户在网站上看到新类(class)的更新。使用 Courses 的查询集,我想通过电子邮件发送它们。

send_daemon_email.delay(instance=instance,all_courses=Course.objects.all()) 

我的函数看起来像:

@shared_task 
def send_daemon_email(instance,all_courses): 
    ctx = {'instance':instance,'all_courses':all_courses} 
    message = get_template("emails/ads.html").render(ctx) 
    ''' ''' 

当我尝试将电子邮件发送给特定用户时 我得到的错误是

<User: First Name> is not JSON serializable

仅仅因为delay()从 celery 得到了一个非序列化的数据。

如何将 Django 对象发送到 celery 任务以便在模板中使用它?我知道我可以将所需的信息作为 python 对象发送

send_daemon_email.delay(first_name='Name', 
      last_name='Lapr',all_courses = [{'title1':'title1',},{'title2':'title2',}]) 

但这会是太多的信息。

任何提示将不胜感激。 谢谢!

请您参考如下方法:

Django 对象无法在 celery 任务中发送,您可以通过提供模板中所需的字段和查找将像模板中的 django 对象一样工作

NOTE: with serializer you will need to dump and load the data

或者只是将您的查询集转换为如下列表:

send_daemon_email.delay( 
    instance = User.objects.filter(pk=user.pk).values('first_name','last_name'), 
    all_courses= list(Course.objects.values('title','other_field')) 
) 

您只需在模板中使用 values('')

提供您真正需要的字段
@shared_task 
def send_daemon_email(instance,all_courses): 
    ctx = { 
        'instance': instance, 
        'all_courses': all_courses, 
    } 
    message = get_template("emails/ads.html").render(ctx) 

在模板中 {% for course in all_courses %}{{course}}{% endfor %} 将显示所有类(class),并且 {{ instance.first_name }} 用户