我有一个 django admin 表格内联,其中我有form = ProdForm
其中持有一个modelchoicefield
选择框如下;
class ProdForm(forms.ModelForm):
productid = forms.ModelChoiceField(queryset=Product.objects.filter(active=True),
widget=Select2(select2attrs={"width": "400px"}), )
如您所见,我正在使用 easy_select2 模块,它也可以为我提供查找字段。
但是,如果我尝试将其加载到相应的 tabularInLine 中,它永远不会加载,因为记录数量非常多(假设有数百万)。因此加载整个查询集是不可能的。我需要找到一种方法来做到这一点,以便使用管理员的人可以搜索他们需要的对象,假设通过名称,这是属性之一Product model
.
一个想法是保留搜索框,但最初不加载查询集,并在搜索字段中有 3 个或更多字母时访问数据库,这可能会起作用。然而,这将包括一些我不太熟悉的 js,我更喜欢一些 pythonic/django 方式来做到这一点。
或者也许有一个很好的 django 方法,但我还没有找到它,我已经束手无策了。
我将不胜感激任何建议。
尝试使用ajax。
您可以致电ajax
当您提交搜索栏时,接下来搜索您的记录view.py
,最后在控制台或模板中显示结果。
这是一个一般示例:
file.js
$("#search").submit(function(e){
e.preventDefault();
$.ajax({
type: 'GET',
url: path_to_view,
data: {'data':data_from_search_bar},
success: function(response){
var result = response['result']
console.log(result)
}
error: 'some_func..'
})
});
view.py
def get_result(request):
if request.is_ajax and request.method =="GET":
response_data = request.GET['data']
product = ProductModel.objects.get(name=response_data)# or others attrs
return JsonResponse({'result':product},status=200)
在这里阅读有关 ajax 的更多信息:
CFE https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html
多元视野 https://www.pluralsight.com/guides/work-with-ajax-django
极客之极客 https://www.geeksforgeeks.org/handling-ajax-request-in-django/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)