Kamal
Kamal

Reputation: 11

Save search query result into a model with django

I have the following code in my view. I want to save the query result (if it's true) into another model. How to achieve this?

def scan(request):
    print(request.session)
    if request.method == 'POST':
        srch = request.POST['srh']

        if srch:
            match = ReportModel.objects.filter(Q(serialNumber__iexact=srch))
            if match:
                return render(request, 'admin/scan.html', {'sr': match})
            else:
                messages.error(request, 'No result yet for the requested device!')
        else:
            return redirect('/scan/')

    return render(request, 'admin/scan.html')

Upvotes: 1

Views: 1324

Answers (1)

Tolqinbek Isoqov
Tolqinbek Isoqov

Reputation: 175

There is one way. You can create your own cache.

The logic is these steps:

  1. Let's suppose there is A and B model.
  2. Define search_result field as None in B model.
  3. When you make query(search) through A model just check B.search_result value, if it is None change search_result value to query result(Be sure that your query is executed) and return it. If it is not None return value(B.search_result).
  4. When there is manipulation(insert, delete, update) on your model A change B.search_result to None.

It is the simple caching your data. And when you use all(), filter(**kwargs) methods in queryset it does not execute query, so wrap it into list or dumpt it into json, so than change value of B.search_result.

Upvotes: -1

Related Questions