title: It's possible to perform db operations asynchronously in django?
body: <p>I'm writing a command to randomly create 5M orders in a database.</p>
  <pre><code>def constrained_sum_sample(
      number_of_integers: int, total: Optional[int] = 5000000
  ) -&gt; int:
      &quot;&quot;&quot;Return a randomly chosen list of n positive integers summing to total.
  
      Args:
          number_of_integers (int): The number of integers;
          total (Optional[int]): The total sum. Defaults to 5000000.
  
      Yields:
          (int): The integers whose the sum is equals to total.
      &quot;&quot;&quot;
  
      dividers = sorted(sample(range(1, total), number_of_integers - 1))
      for i, j in zip(dividers + [total], [0] + dividers):
          yield i - j
  
  
  def create_orders():
      customers = Customer.objects.all()
      number_of_customers = Customer.objects.count()
      for customer, number_of_orders in zip(
          customers,
          constrained_sum_sample(number_of_integers=number_of_customers),
      ):
          for _ in range(number_of_orders):
              create_order(customer=customer)
  </code></pre>
  <p><code>number_of_customers</code> will be at least greater than 1k and the <code>create_order</code> function does at least 5 db operations (one to create the order, one to randomly get the order's store, one to create the order item (and this can go up to 30, also randomly), one to get the item's product (or higher but equals to the item) and one to create the sales note.</p>
  <p>As you may suspect this take a LONG time to complete. I've tried, unsuccessfully, to perform these operations asynchronously. All of my attempts (dozen at least; most of them using <code>sync_to_async</code>) have raised the following error:</p>
  <pre><code>SynchronousOnlyOperation you cannot call this from an async context - use a thread or sync_to_async
  </code></pre>
  <p>Before I continue to break my head, I ask: is it possible to achieve what I desire? If so, how should I proceed?</p>
  <p>Thank you very much!</p>