Django admin表格内联查找选择下拉框,用于非常大的查询集 [英] Django admin tabular inline lookup select dropdown box for a very large queryset

查看:151
本文介绍了Django admin表格内联查找选择下拉框,用于非常大的查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django admin表格内联,其中有 form = ProdForm ,其中包含一个 modelchoicefield 选择框,如下所示;

I have a django admin tabular inline, in which I have form = ProdForm which holds a modelchoicefield select box as follows;

class ProdForm(forms.ModelForm):
    productid = forms.ModelChoiceField(queryset=Product.objects.filter(active=True),
                                       widget=Select2(select2attrs={"width": "400px"}), )

如您所见,我正在使用easy_select2模块,该模块也使我也可以提供查找字段.

as you can see, I am using the easy_select2 module, that is enabling providing me with a look up field too.

但是,如果我尝试将其加载到相应的tabularInLine中,则它永远不会加载,因为存在大量记录(假设数百万个).因此,无法加载整个查询集.我需要找到一种方法来执行此操作,以便使用管理员的人员可以搜索所需的对象,并假设其名称是 Product model 上的属性之一.

However, if I try to load this in the corresponding tabularInLine, it never loads because there is a very high number of records (suppose millions). Therefore loading the entire queryset is not possible. I need to find a way to do this so people using the admin can search the object they need, suppose by a name which is one of the attributes on the Product model.

一个想法是保留搜索框,但最初不加载查询集,并且当搜索字段中有3个或更多字母可能有效时,请点​​击db.但是,其中将包含一些我不太熟悉的js,我更喜欢采用pythonic/django的方式.

An idea is to keep the search box but not load the queryset initially and hit the db when there are, for example 3 or more letters in the search field, that could maybe work. However, that would include some js that I am not really familiar with and I would prefer some pythonic/django way of doing this.

或者也许有一个不错的django方式,但是我还没有找到,我处于机智.任何建议,我将不胜感激.

Or maybe there is a nice django way but I haven't found it and I am at my wits end. I would appreciate any suggestions.

推荐答案

尝试使用Ajax.

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

You can call ajax when you submit search bar, next search your record in view.py, and at the end display result in console or template.

这是一个一般示例:

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的更多信息:

Read here more about ajax:

CFE

复数

geeksforgeeks

这篇关于Django admin表格内联查找选择下拉框,用于非常大的查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆