Skip to main content
 首页 » 编程设计

python之Django 数据库查询往返

2024年11月01日37jackei

我有下面的查询,正如您在我的循环中看到的那样,我添加了每条消息。我想减少我必须对数据库进行的总往返次数。这是我可以一次处理 20 条批量创建的消息的方法吗?这对速度有帮助吗?欢迎任何建议。

class ProcessRequests(Task): 
    """ 
    Celery Task to start request to process that are not scheduled. 
    """ 
    name = "Request to Process" 
    max_retries = 1 
    default_retry_delay = 3 
 
    def run(self, batch): 
        # Only run this task on non-scheduled tasks 
        if batch.status != "Scheduled": 
            q = Contact.objects.filter(contact_owner=batch.user, subscribed=True) 
            if batch.group == None: 
                q = q.filter(id=batch.contact_id) 
            else: 
                q = q.filter(group=batch.group) 
 
            for e in q: 
                msg = Message.objects.create( 
                    recipient_number=e.mobile, 
                    content=batch.content, 
                    sender=e.contact_owner, 
                    billee=batch.user, 
                    sender_name=batch.sender_name 
                ) 
                gateway = Gateway.objects.get(pk=2) 
                msg.send(gateway) 

请您参考如下方法:

您可以使用 bulk_create .

另请注意,您每次通过循环都会获得相同的 gateway 对象,最好在循环外获得一次并每次都使用相同的对象。