2013-08-22 84 views
2

我有下面的查詢,你可以在我的循環中看到我添加每條消息。我想減少我必須對數據庫進行的總體往返行程。這是我可以一次處理20個分批創建的消息嗎?這對速度有幫助嗎?歡迎任何建議。Django數據庫查詢往返

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) 

回答

2

您可以使用bulk_create

另請注意,每次通過循環時都會得到相同的對象gateway,所以最好在循環外部使用它,並且每次都使用同一個對象。

+0

感謝您的幫助:) – GrantU