Django admin tabular inline lookup select dropdown box for a very large queryset

时光毁灭记忆、已成空白 提交于 2021-01-29 15:25:43

问题


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"}), )

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

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.

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.

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.


回答1:


Try to use ajax.

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.

This is a general example:

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)

Read here more about ajax:

CFE

pluralsight

geeksforgeeks



来源:https://stackoverflow.com/questions/65216856/django-admin-tabular-inline-lookup-select-dropdown-box-for-a-very-large-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!