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
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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.