Django表单与ManyToMany字段有50万个对象超时 [英] Django form with ManyToMany field with 500,000 objects times out
问题描述
class PhoneNumbers(models $ M $)
$ = $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
类客户端(models.Model):
number = forms.ManyToManyField(PhoneNumbers)
客户端与PhoneNumbers有一个ManyToMany关系。 PhoneNumbers拥有近五十万条记录,所以当使用一个M2M站点的MultiSelect小部件从模型窗体中编辑客户端记录时,它将永远加载。其实,它从来没有。它只是坐在那里试图加载我假设的所有手机对象。
我的解决方法是使用ajax和jquery来编辑客户端记录中的电话号码。在浪费我所有的时间之前,我想看看有没有另一种方式去做,而不让我的页面挂起。
您需要为此字段创建一个自定义窗口小部件,让您自动填充正确的记录。如果您不想自己滚动: http://django-autocomplete-light.readthedocs.io /
我已经将其用于通用关系支持,M2M自动完成看起来也很简单直观。请参阅此处使用的视频: http://www.youtube.com/watch ?v = fJIHiqWKUXI& feature = youtu.be
在阅读关于在管理员之外需要的评论之后,我再次看看 django-autocomplete-light
库。 它提供了您可以在外面使用的小部件管理员。
从dal import autocomplete
from django import forms
class PersonForm(forms.ModelForm):
class Meta:
widgets = {
'myformfield':autocomplete.ModelSelect2(
#...
),
}
Lets say for example I have a Model called "Client" and a model called "PhoneNumbers"
class PhoneNumbers(models.Model):
number = forms.IntegerField()
class Client(models.Model):
number = forms.ManyToManyField(PhoneNumbers)
Client has a ManyToMany relationship with PhoneNumbers. PhoneNumbers has almost 500,000 records in it so when it comes to editing a Client record from a model form with a MultiSelect widget that comes with a M2M filed, it takes forever to load. In fact, it never does. It just sits there trying to load all of those phone objects I am assuming.
My workaround was to so some tedious things with ajax and jquery to edit only the phone numbers in a Client record. Before wasting my time with all of that I wanted to see if there is somehow another way to go about it without having my page hang.
You need to create a custom widget for this field that lets you autocomplete for the correct record. If you don't want to roll your own: http://django-autocomplete-light.readthedocs.io/
I've used this for its generic relationship support, the M2M autocomplete looks pretty easy and intuitive as well. see video of use here: http://www.youtube.com/watch?v=fJIHiqWKUXI&feature=youtu.be
After reading your comment about needing it outside the admin, I took another look at the django-autocomplete-light
library. It provides widgets you can use outside the admin.
from dal import autocomplete
from django import forms
class PersonForm(forms.ModelForm):
class Meta:
widgets = {
'myformfield': autocomplete.ModelSelect2(
# ...
),
}
这篇关于Django表单与ManyToMany字段有50万个对象超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!