Many to Many field in ModelForm - with tens of thousands of records

55 views
Skip to first unread message

Web Architect

unread,
Oct 29, 2018, 7:18:54 AM10/29/18
to Django users
Hi,

We are using django 1.11 for our ecommerce site. 

We are facing an issue with modelform and many to many field in it as follows:

Lets say there are two models:

class A(models.Model):
       c = models.CharField()

class B(models.Model):
      a = models.ManyToManyField('A')

Now if I define a modelform:

class MF(models.ModelForm):
      class Meta:
              model = B
              fields = [a,]

We are using django widget tweaks to render the fields in MF. Now if there are tens of thousands of records in A, the MF form rendering causes the page to hang as the widget will try to show the whole set of tens of thousands of records option for field a. 

Hence, would appreciate if anyone could suggest a smart solution wherein the above issue is taken care of. 

Thanks.


Web Architect

unread,
Oct 29, 2018, 7:30:48 AM10/29/18
to Django users
Would also add that the server CPU usage was hitting 100% due to the template loading issue. 

Sanjay Bhangar

unread,
Oct 29, 2018, 7:39:50 AM10/29/18
to django...@googlegroups.com
My recommendation would be to use a bit of Javascript to implement an
"autocomplete" to fetch records via AJAX as the user types (with
perhaps a minimum of 3 characters or so), so you only ever fetch a
subset of records and don't overload your template.

You can find quite a few 3rd party libraries that should be able to
aid in setting up this behaviour, see:
https://djangopackages.org/grids/g/auto-complete/ - unfortunately, I
can't recommend a particular one right now - but most should have
integrations for the django admin / django forms with Many2Many or
ForeignKey fields.

Hope that helps,
Sanjay
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/36ebab2d-7440-40bc-b5e9-a4a2897dcd3a%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Web Architect

unread,
Oct 29, 2018, 8:13:35 AM10/29/18
to Django users
Hi Sanjay,

Thanks for the prompt response and the approach. 

That seems to be an efficient approach - would look into auto-complete.

Thanks.
Reply all
Reply to author
Forward
0 new messages