Async creation of models on form save

46 views
Skip to first unread message

Alexander Halford

unread,
Aug 18, 2018, 4:10:15 PM8/18/18
to django...@googlegroups.com
Hi,

I have a ‘company’ model, and each company, when created via a form, has a given number of assets. The fun bit, is that the asset is a model in its own right. To achieve this, I’ve done the following:

class CompanyCreateView(LoginRequiredMixin, CreateView):

form_class = CompanyCreationForm
template_name = 'create_company.html'
redirect_unauthenticated_users = True
success_url = '/users/my_companies'

def form_valid(self, form):
form.instance.admin = self.request.user
form.instance.is_validated = False
company = form.save()

for n in range(form.instance.asset_number):
Asset.objects.create_asset(company, company.admin)

some other stuff

return super().form_valid(form)

This works fine, but sometimes, the asset number is large (100,000). This causes the submission of the form to be incredibly slow (about a minute).

Since it is not necessary for the asset models to be available immediately (there is a whole email validation process before the user can actually access anything), could I make the creation of the Asset objects async, so the form is accepted immediately, and the process to create the Assets finishes whenever it’s finished?

The manager is like this:

class AssetManager(models.Manager):
def create_asset(self, company, owner):
Asset = self.create(company=company, owner=owner)
return asset

Is this possible, or am I barking up the wrong tree?

Christophe Pettus

unread,
Aug 18, 2018, 4:13:33 PM8/18/18
to django...@googlegroups.com

> On Aug 18, 2018, at 13:09, 'Alexander Halford' via Django users <django...@googlegroups.com> wrote:
> Is this possible, or am I barking up the wrong tree?

It's certainly possible for a synchronous web request to trigger an async action; look at Celery, among other background task managers:

http://www.celeryproject.org

--
-- Christophe Pettus
x...@thebuild.com

Reply all
Reply to author
Forward
0 new messages