为什么在Django应用程序中使用Ajax和Json进行CRUD操作如此缓慢?如果有7000条记录是个问题,我如何将它提高到秒?

时间:2021-03-04 04:15:37

I am performing operations on remote legacy MySQL database having about 7000 records.Currently, it's taking around 1.5 minutes for the Update / Delete / Create operation.I have also imported necessary files which is not included in Views.py below.

我正在对具有大约7000条记录的远程遗留MySQL数据库执行操作。目前,更新/删除/创建操作大约需要1.5分钟。我还导入了视图中不包含的必要文件。py如下。

Is using dict() a problem? Should I use Rest? OR some other API. Any suggestions will be appreciated!

使用dict()是一个问题吗?我应该用休息吗?或其他API。如有任何建议将不胜感激!

Here is the code:

这是代码:

plugin.js

plugin.js

$(document).ready(function(){
var ShowForm = function(){
    var btn = $(this);
    $.ajax({
        url: btn.attr("data-url"),
        type: 'get',
        dataType:'json',
        beforeSend: function(){
            $('#modal-book').modal('show');
        },
        success: function(data){
            $('#modal-book .modal-content').html(data.html_form);
        }
    });
};

var SaveForm =  function(){
    var form = $(this);
    $.ajax({
        url: form.attr('data-url'),
        data: form.serialize(),
        type: form.attr('method'),
        dataType: 'json',
        success: function(data){
            if(data.form_is_valid){
                $('#book-table tbody').html(data.book_list);
                $('#modal-book').modal('hide');
            } else {
                $('#modal-book .modal-content').html(data.html_form)
            }
        }
    })

    return false;
}

// create 

$(".show-form").click(ShowForm);
$("#modal-book").on("submit",".create-form",SaveForm);

//update

$('#book-table').on("click",".show-form-update",ShowForm);
$('#modal-book').on("submit",".update-form",SaveForm)

//delete

$('#book-table').on("click",".show-form-delete",ShowForm);
$('#modal-book').on("submit",".delete-form",SaveForm)

});

Views.py

Views.py

 # Fetching records with pagination

 @login_required()
 def book_list(request):
 books = AvailstaticCopy.objects.all().order_by('-row_date')
 page = request.GET.get('page', 1)

 paginator = Paginator(books, 144)
 try:
    books = paginator.page(page)
 except PageNotAnInteger:
    books = paginator.page(1)
 except EmptyPage:
    books = paginator.page(paginator.num_pages)

 context = {
 'books': books
 }
 return render(request, 'books/book_list.html',context)

@login_required()
def save_all(request,form,template_name):

data = dict()
if request.method == 'POST':
    if form.is_valid():
        form.save()
        data['form_is_valid'] = True
        books = AvailstaticCopy.objects.all()
        data['book_list'] = render_to_string('books/book_list_2.html',
        {'books':books})
    else:
        data['form_is_valid'] = False
  context = {
  'form':form
 }
 data['html_form'] = render_to_string(template_name,context,request=request)
 return JsonResponse(data)

# Create new record

@login_required()
def book_create(request):
if request.method == 'POST':
    form = AvailForm(request.POST)
else:
    form = AvailForm()
return save_all(request,form,'books/book_create.html')

# Update record

@login_required()
def book_update(request,id):
 book = get_object_or_404(AvailstaticCopy,id=id)
 if request.method == 'POST':
    form = AvailForm(request.POST,instance=book)
 else:
    form = AvailForm(instance=book)
return save_all(request,form,'books/book_update.html')

 # Delete Record

@login_required()
def book_delete(request,id):
 data = dict()
 book = get_object_or_404(AvailstaticCopy,id=id)
 if request.method == "POST":
    book.delete()
    data['form_is_valid'] = True
    books = AvailstaticCopy.objects.all()
    data['book_list'] = render_to_string('books/book_list_2.html',
    {'books':books})
 else:
    context = {'book':book}
    data['html_form'] = 
 render_to_string('books/book_delete.html',context,request=request)

 return JsonResponse(data)

2 个解决方案

#1


0  

I suppose, your problem is in server responses. In all views where you change server data (delete, update, create) you try return updated book list, but you do not paginate book queryset, and django template processor take a lot of time to prepare html with all books. I suggest you add function which will paginate queryset like this:

我想,您的问题在于服务器响应。在您更改服务器数据(删除、更新、创建)的所有视图中,您尝试返回更新的图书列表,但是您不需要分页的book queryset, django模板处理程序需要花费大量的时间准备html和所有的书籍。我建议您添加这样的函数来分页queryset:

def get_book_page(request, books):
    page = request.GET.get('page', 1)
    paginator = Paginator(books, 144)
     try:
        books = paginator.page(page)
     except PageNotAnInteger:
        books = paginator.page(1)
     except EmptyPage:
        books = paginator.page(paginator.num_pages)
    return books

And wrap all book querysets in your views. Also it will be needed add to urls page number as get parameter (for example /update-book/1?page=2) because if you don't do it, it won't be work.

并将所有图书查询集打包到视图中。还需要将它添加到url页号作为get参数(例如/ updatebook /1?page=2),因为如果不这样做,就无法工作。

#2


0  

Thanks for giving me a hint.That worked! I have paginated queryset like this:

谢谢你给我一个提示。那工作!我有这样的分页查询集:

def save_all(request,form,template_name):

  data = dict()
  paginate_by = 144

  if request.method == 'POST':
    if form.is_valid():
        form.save()
        data['form_is_valid'] = True
        books = AvailstaticCopy.objects.all().order_by('-row_date')
        page = request.GET.get('page', 1)
        paginator = Paginator(books, 144)
        try:
            books = paginator.page(page)
        except PageNotAnInteger:
            books = paginator.page(1)
        except EmptyPage:
            books = paginator.page(paginator.num_pages)
        data['book_list'] = render_to_string('books/book_list_2.html',
        {'books':books})

    else:

        data['form_is_valid'] = False
 context = {
 'form':form
 }
 data['html_form'] = render_to_string(template_name,context,request=request)
 return JsonResponse(data)

#1


0  

I suppose, your problem is in server responses. In all views where you change server data (delete, update, create) you try return updated book list, but you do not paginate book queryset, and django template processor take a lot of time to prepare html with all books. I suggest you add function which will paginate queryset like this:

我想,您的问题在于服务器响应。在您更改服务器数据(删除、更新、创建)的所有视图中,您尝试返回更新的图书列表,但是您不需要分页的book queryset, django模板处理程序需要花费大量的时间准备html和所有的书籍。我建议您添加这样的函数来分页queryset:

def get_book_page(request, books):
    page = request.GET.get('page', 1)
    paginator = Paginator(books, 144)
     try:
        books = paginator.page(page)
     except PageNotAnInteger:
        books = paginator.page(1)
     except EmptyPage:
        books = paginator.page(paginator.num_pages)
    return books

And wrap all book querysets in your views. Also it will be needed add to urls page number as get parameter (for example /update-book/1?page=2) because if you don't do it, it won't be work.

并将所有图书查询集打包到视图中。还需要将它添加到url页号作为get参数(例如/ updatebook /1?page=2),因为如果不这样做,就无法工作。

#2


0  

Thanks for giving me a hint.That worked! I have paginated queryset like this:

谢谢你给我一个提示。那工作!我有这样的分页查询集:

def save_all(request,form,template_name):

  data = dict()
  paginate_by = 144

  if request.method == 'POST':
    if form.is_valid():
        form.save()
        data['form_is_valid'] = True
        books = AvailstaticCopy.objects.all().order_by('-row_date')
        page = request.GET.get('page', 1)
        paginator = Paginator(books, 144)
        try:
            books = paginator.page(page)
        except PageNotAnInteger:
            books = paginator.page(1)
        except EmptyPage:
            books = paginator.page(paginator.num_pages)
        data['book_list'] = render_to_string('books/book_list_2.html',
        {'books':books})

    else:

        data['form_is_valid'] = False
 context = {
 'form':form
 }
 data['html_form'] = render_to_string(template_name,context,request=request)
 return JsonResponse(data)