0

我有一个 django admin tabular inline,其中有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 方式,但我还没有找到它,而且我束手无策。我将不胜感激任何建议。

4

1 回答 1

1

尝试使用ajax。

您可以ajax在提交搜索栏时调用,下次在 中搜索您的记录view.py,最后在控制台或模板中显示结果。

这是一个普遍的例子:

文件.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..'
    })
});

视图.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

复视

极客

于 2020-12-09T13:16:05.753 回答