How to minimise the django search query? - django

I am planning to implement a live autosearch complete function in django ! But, am belive that am over doing it, so need a suggestion:
Basically this search bar is located in a page, where all at first all the available data's are displayed as a list ! And then when user types something i filter it out using jquery autocomplete.
In the above, am making two queries one to get all data and another one on each user types
As this takes two query, i belive its inefficient
Here is my search function
def search_query(request):
if 'term' in request.GET:
qs = University.objects.filter(name__icontains=request.GET.get('term'))
names = list()
for data in qs:
names.append(data.name)
return JsonResponse(names, safe=False)
And the above is been called each time the user types in the search bar and this is my jquery autocomplete code:
<script>
$( function() {
$( "#tags" ).autocomplete({
source: "{% url 'students:search-query' %}" // this hits the above def
});
} );
</script>
Apart from this, am also making this to show full list as initial data,
def index(request):
univesity = University.objects.filter(published=True)
context = {'univesity': univesity}
return render(request, 'students/search/index.html', context)
is this right way or is there any effcient way ? Can both the queries be combined or please suggest a efficient solution ( approx 50,000 datas to be searched as of now, may increase )

First off, both queries are returning different data. The index returns only published universities while the search returns all.
There are two solutions to your problem. Either one should work. Go with whichever you're more comfortable with (i.e if you write only Python improve the query, if you prefer JS do it on the frontend)
Performing the search on the Frontend
Now since you're returning all the data to the frontend, you can simply give it all to Jquery's autocomplete as a source and let it all happen on the frontend itself.
This can simply be something like
<script>
var universities = [] // populated either via an API or HTML rendering
$( function() {
$( "#tags" ).autocomplete({
source: universities.map(uni => uni.name),
});
});
</script>
OR
<script>
var universities = [] // populated either via an API or HTML rendering
function filterUniversities(request, response) {
var filteredNames = universities.filter(uni => uni.name === request).map(uni => uni.name);
response(filteredNames);
}
$( function() {
$( "#tags" ).autocomplete({
source: filterUniversities,
});
});
</script>
In either case you first need to set the list of universities. Looking at your code I see that you're rendering the data so an API is out of the question. You can do something like
<script>
var universities = [{% for uni in universities %}{{ uni }}{% if not forloop.last %}, {% endif %}{% endfor %}]
</script>
You might need to replace the {{ uni }} part with appropriate code.
There is also something called json_script that I've never tried but might work better.
{{ universities|json_script:"university-data" }}
And then your script simply becomes
<script>
var universities = JSON.parse(document.getElementById('university-data').textContent);
$( function() {
$( "#tags" ).autocomplete({
source: universities.map(uni => uni.name),
});
});
</script>
The first one will slow down your initial render time since the frontend has to compute that list right at the start.
The second will make every search slow instead.
Of course both these delays are in ms and should be much lesser than making a call to the server.
Improving backend query
If you prefer to still keep the search async and call your search query method each time, you can increase the delay before auto complete makes the call. By default it waits 300ms after the user stops typing before making performing the search.
In terms of the actual query
def search_query(request):
term = request.GET.get('term')
if term:
names = list(
University.objects
.filter(name__icontains=request.GET.get('term'))
.values_list("name", flat=True)
)
return JsonResponse(names, safe=False)
The main changes here are:
We're fetching only the university names from the db. Each university might contain lots of data, fetching it all can be slow. If we fetch only what's needed it's much quicker.
We're casting the queryset to a list rather than building a new list with append. Doing append in a loop is the slowest way of creating a list. List comprehensions is much quicker, but in this case we don't even need that. Simply casting to a list is the quickest.
We've also taken the term into a variable and checked that. Not a huge speed gain but if the term is blank (i.e request.GET['term'] = '') we don't want to do the search. 50k rows shouldn't be a lot for any database.
If you still find that the db is too slow you will need to analyse your queries and see how it can be optimized. Some sort of index might be needed, but that is beyond the scope of this answer, and should mostly likely not be necessary.

Related

Separate Kendo Scheduler Editor Templates

Am I able to load a custom template based on a condition?
eg..
If I was making a booking for a mechanic then the editor form would show textboxes for carmodel, yearmake etc.
If I was making a booking for a carpet cleaner the editor form would show textboxes for howmanyrooms, room sizes etc..
Am I able to pass an ID of a service and show the particular editor form for the correct service?
we can currently display this functionality if we create different scheduler Views but that would then create a duplication of many pages.
I had the exact same problem and after searching a long time and combining what I found, I came to this :
1) above my scheduler I have a kendodropdownlist
<input id="reservationPicker" />
<script>
$("#reservationPicker").kendoDropDownList({
dataTextField: "name",
dataValueField: "reservationDefTypeId",
dataSource: reservationPickerDataSource
});
</script>
2) my event has an extra field reservationDef which will hold the information of the dropdownlist.
3) I can use this information in my template
<script id="editorScheduler" type="text/x-kendo-template">
<center>
<div id="main">
#if(reservationDef=="mechanic"){#
<h3>Mechanic stuff</h3>
#}else if(reservationDef=="carpetCleaner"){#
<h3>Carpet Cleaner stuff</h3>
#}else{#
<h3>unknown type of reservation !</h3>
#: reservationDef #
#}#
</div>
</center>
</script>
4) I use this template in my scheduler
editable: {
template: $("#editorScheduler").html()
},
5) but what with a new appointment ! I use the add event of the scheduler and I fill in this information in the event
add: function (e) {
var reservationTypes = $("#reservationPicker").data("kendoDropDownList");
var selectedReservationType = reservationTypes.dataItem();
e.event.reservationDef = selectedReservationType.appointmentTitle;
},
This does the trick for me. Good luck !
No I didn't but I did find a work around by dynamically adding textboxes on the following page. To b able to choose a view model at runtime for the scheduler didn't seem possible
if anyone knows how to load a particular viewmodel at runtime using mvc would be very intresting for future ideas and development.

Getting checkbox value in flask

I'm trying to poll the state of checkboxes (this is done in JS every three seconds). This solution returns "None" (see code below); Both printouts (with 'args' and with 'form') return "None". I'm expecting True/False, depending on the checkbox's boolean state.
index.html:
{% extends "layout.html" %}
{% block content %}
<div id="results" class="container">{{data_load|safe}}</div>
<input id='testName' type='checkbox' value='Yes' name='testName'>
{% endblock %}
and the relevant flask app snippet:
#app.route('/', methods = ['GET', 'POST'])
def index():
return render_template('index.html', data_load=timertry())
#app.route('/_timertry', methods = ['GET', 'POST'])
def timertry():
print request.args.get('testName')
print request.form.get('testName')
return "some html going into 'results' div.."
The JavaScript polling function (adapted from here):
$(document).ready(function() {
$.ajaxSetup({cache : false});
setInterval(function() {
$('#results').load('/_timertry?' + document.location );
}, 3000); // milliseconds!
});
This should be simple enough, but none of the SO solutions I looked into (e.g., using jquery, adapting the flask/ajax example, etc.) worked.
EDIT: following mark's suggestion (including the javascript) and adding
print request.values in index.html returns (seen on the console in Aptana):
CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([])])
Clearly, the request seems empty. The post request is logged (when checkbox is pressed) as:
127.0.0.1 - - [03/Oct/2013 00:11:44] "POST /index HTTP/1.1" 200 -
Any ideas here?
Your javascript does the following every three seconds...
$('#results').load('/_timertry?' + document.location);
In other words, you are using the jQuery load() function. The documentation for that function states that this will, in essence, call an HTTP get request to the URL you provide as the parameter (something like /_timertry?http://www.example.org. In other words, a GET request will be called to /timertry?http://www.example.org, which will be handled by Flask's timertry method.
When you have an HTTP form, and you click the "Submit" button, the browser does some magic to push all of the values to the server in the request. When you just do a simple AJAX request, none of that happens for you. Instead, you need to explicitly state what you want to be passed as data to the server (although there are plugins to help you with "post the values of an HTML form using AJAX").
So, because at no point did you do anything in your Javascript to retrieve the value of checkbox to include it into the AJAX request, the AJAX request has no values specifying that the checkbox was checked. You would need to have jQuery check if the box is checked...
var isChecked = $('#testName').is(':checked');
# Now do something with isChecked...
From what I can tell, however, you are sort of misusing HTTP: the load function will make a GET request, and you probably want something to happen as a request of the request. You probably want to make it do a POST request instead (see here and here). Also, you mentioned that you're looking for something to post when a value is changed. Putting this together, you can do something like this...
// Ensure that the function is called when the DOM is ready...
$(function() {
// Register an event that should be fired when the checkbox value is changed
$('#testName').change(function() {
var data = { isChecked : $(this).is(':checked') };
$.post('/', data);
});
})
In this case, we have an event that is called when a checkbox is checked, and that event causes us to make a POST request to the server.
I'm going to answer this question which was found in the comments of the question
"which becomes a question of how to submit a form without a 'submit' button.."
So it is very possible to submit a value when a user clicks on the button
{% block content %}
<form id="target" action="YourViewName">
<div id="results" class="container">{{ data_load|safe }}</div>
<input id='testName' type='checkbox' value='Yes' name='testName'>
</form>
{% endblock %}
$( "#results" ).click(function() {
$( "#target" ).submit();
});
If you want to stay on the same page, however, you're going to need to use an ajax call to pass the data back rather then use a standard submit, however This tutorial covers that topic fairly well. but a basic change to send the data back would look like
$( "#results" ).click(function() {
var request = $.ajax({
type: "POST",
url: "/YourViewName",
data: {'input_value':$('#testName').val()},
dataType: "html"
}).done(function(msg) {
// I don''t know what you want to do with a return value...
// or if you even want a return value
}
});
and the flask would look like
#app.route("/YourViewName")
def example():
list_name = request.args.get("input_value")
#if you don't want to change the web page just give a blank return
return ""

Django/Haystack - best option to have a listview with search capability

I have an app with a Restaurant model. I'd like to understand what is the best way to put together a view that displays the list of restaurant objects, but also has a search form above that a user could enter parameters to filter the results displayed. If no parameters are entered, all the restaurants should be shown. I'm already using haystack and have a search form, but currently it is on a standalone search.html template. I also have an ListView on a separate template, and I guess I'm looking for an end result that combines these.
I did some reading on line and it's unclear what the best way to do it is:
using just listview from Django with some queryset filtering
combining haystack SearchView with django class based views?
this is my best bet so far - creating a customized version of SearchView from Haystack
ideally, ultimately the search capabilities would include things like allow autocompleting the user's inputs, and dynamically filter the results as the user types.
any thoughts on what the best way is to go about this and any examples out there?
There probably is out there some package that gives you everything automatically, displaying the queryset list and allowing simple adding of a search bar and so on (like the admin site). But I take it you are still a beginner to web development, so I'd strongly suggest you drop the listviews, drop haystack, drop everything, and do it all yourself.
See, they're not bad approaches or anything, but they're like shortcuts. And shortcuts are good only if they shorten the original way, which in your case isn't all that long.
To give you an example, here's a simple approach to displaying a list of items:
views.py
def restaraunt_list(request):
restaraunts = Restaraunt.objects.all().order_by('name')[:100] # Just for example purposes. You can order them how you'd like, and you probably want to add pagination instead of limiting the view number arbitrarily
context = {'restaraunts': restaraunts}
return render_to_response('index.html', context)
index.html:
<ul>
{% for rest in restaraunts %}
<li>{{ rest }}</li>
{% endfor %}
</ul>
That's it. Now it displays it in a list. Now to add a search filter all you need to do is this:
index.html (add this anywhere you want it)
<form>
<input type='text' name='q' id='q'></input>
<input type='submit' value='search!'></input>
</form>
When a user sends the data from 'q' it is sent through GET, and then on server side you add this:
def restaraunt_list(request):
restaraunts = Restaraunt.objects.all()
# filter results!
if request.method == 'GET':
q = request.GET['q']
if q != '':
restaraunts = restaraunts.filter(name__contains=q)
# ordering is the last thing you do
restaraunts = restaraunts.order_by('name')[:100]
context = {'restaraunts': restaraunts}
return render_to_response('index.html', context)
Now, this will work, but from what you wrote I understand you want the search to be live the moment a key is pressed. For that, you'd need to use AJAX (go learn how it works, I'm not gonna delve into it here). As for autocomplete, you should check out jQuery UI.
But, like I said, before jumping ahead and using all those stuff, I suggest you first learn the basics. Go through the django tutorial (if you haven't already), and use the amazingly detailed django-docs every step of the way. When some specific things won't work and you're stuck, come here to Stackoverflow and someone will surely help you. good luck!

Django Flowplayer overlay does not submit form

I am trying to use flowplayer's overlay to load an external page that has a django form built in.
However the overlay loads the page but the submit button simply refreshes the page.
How do i actually submit the values entered in the form?
<script src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>
<script>
$(function() {
// if the function argument is given to overlay,
// it is assumed to be the onBeforeLoad event listener
$("a[rel]").overlay({
mask: {
color: '#ebecff',
loadSpeed: 200,
opacity: 0.9
},
effect: 'apple',
closeOnClick: false,
onBeforeLoad: function() {
// grab wrapper element inside content
var wrap = this.getOverlay().find(".contentWrap");
// load the page specified in the trigger
wrap.load(this.getTrigger().attr("href"));
}
});
});
</script>
<div class="bananas">launch</div>
my view boom has a model form.
Without seeing the actual view code, it's hard to give a helpful answer. In the future, please be sure to do so...
If you don't have the overlay programmed to redirect to the page, then submitting it to that same url might process/save the data without you noticing. Is the data being saved, or does absolutely nothing happen when you click 'submit'?
Generally, this is how it works: you need to be posting to a url, defined in urls.py, that points to a view function in your views.py. (These names are merely convention, and can be called whatever you like) You mentioned that you have a view named 'boom': is it defined in your urls.py like this?
url(r'^path/to/boom/$', 'model.views.boom',),
Check that this is defined and that your form is posting to it.
The view must then contain logic to process the request and return a response. Posting to that url will transfer a cleaned_data dictionary of form variables that can be accessed over the field names defined in the form. It looks like this: x = form.cleaned_data[x]. Check the form for its validity with form.is_valid(), and then do your processing. This can involve saving objects, running arbitrary code, whatever you wish.
To find out more, be sure to read the excellent documentation.

jquery-autocomplete does not work with my django app

I have a problem with the jquery-autocomplete pluging and my django script. I want an easy to use autocomplete plugin. And for what I see this (http://code.google.com/p/jquery-autocomplete/) one seems very usefull and easy. For the django part I use this (http://code.google.com/p/django-ajax-selects/) I modified it a little, because the out put looked a little bit weired to me. It had 2 '\n' for each new line, and there was no Content-Length Header in the response. First I thought this could be the problem, because all the online examples I found had them. But that was not the problem.
I have a very small test.html with the following body:
<body>
<form action="" method="post">
<p><label for="id_tag_list">Tag list:</label>
<input id="id_tag_list" name="tag_list" maxlength="200" type="text" /> </p>
<input type="submit" value="Submit" />
</form>
</body>
And this is the JQuery call to add autocomplete to the input.
function formatItem_tag_list(row) {
return row[2]
}
function formatResult_tag_list(row) {
return row[1]
}
$(document).ready(function(){
$("input[id='id_tag_list']").autocomplete({
url:'http://gladis.org/ajax/tag',
formatItem: formatItem_tag_list,
formatResult: formatResult_tag_list,
dataType:'text'
});
});
When I'm typing something inside the Textfield Firefox (firebug) and Chromium-browser indicates that ther is an ajax call but with no response. If I just copy the line into my browser, I can see the the response. (this issue is solved, it was a safety feature from ajax not to get data from another domain)
For example when I am typing Bi in the textfield, the url "http://gladis.org/ajax/tag?q=Bi&max... is generated. When you enter this in your browser you get this response:
4|Bier|Bier
43|Kolumbien|Kolumbien
33|Namibia|Namibia
Now my ajax call get the correct response, but there is still no list showing up with all the possible entries. I tried also to format the output, but this doesn't work either. I set brakepoints to the function and realized that they won't be called at all.
Here is a link to my minimum HTML file http://gladis.org/media/input.html
Has anybody an idea what i did wrong. I also uploaded all the files as a small zip at http://gladis.org/media/example.zip.
Thank you for your help!
[Edit]
here is the urls conf:
(r'^ajax/(?P<channel>[a-z]+)$', 'ajax_select.views.ajax_lookup'),
and the ajax lookup channel configuration
AJAX_LOOKUP_CHANNELS = {
# the simplest case, pass a DICT with the model and field to search against :
'tag' : dict(model='htags.Tag', search_field='text'),
}
and the view:
def ajax_lookup(request,channel):
""" this view supplies results for both foreign keys and many to many fields """
# it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
# in which case we'll support POST
if request.method == "GET":
# we could also insist on an ajax request
if 'q' not in request.GET:
return HttpResponse('')
query = request.GET['q']
else:
if 'q' not in request.POST:
return HttpResponse('') # suspicious
query = request.POST['q']
lookup_channel = get_lookup(channel)
if query:
instances = lookup_channel.get_query(query,request)
else:
instances = []
results = []
for item in instances:
results.append(u"%s|%s|%s" % (item.pk,lookup_channel.format_item(item),lookup_channel.format_result(item)))
ret_string = "\n".join(results)
resp = HttpResponse(ret_string,mimetype="text/html")
resp['Content-Length'] = len(ret_string)
return resp
You probably need a trailing slash at the end of the URL.
Also, your jQuery selector is wrong. You don't need quotes within the square brackets. However, that selector is better written like this anyway:
$("input#id_tag_list")
or just
$("#id_tag_list")
Separate answer because I've just thought of another possibility: is your static page being served from the same domain as the Ajax call (gladis.org)? If not, the same-domain policy will prevent Ajax from being loaded.
As an aside, assuming your document.ready is in your Django template, it would be a good idea to utilize the {% url %} tag rather than hardcoding your URL.
$(document).ready(function(){
$("input[id='id_tag_list']").autocomplete({
url:'{% url my_tag_lookup %}',
dataType:'text'
});
});
This way the JS snippet will be rendered with the computed URL and your code will remain portable.
I found a solution, but well I still don't know why the first approach didn't worked out. I just switched to a different library. I choose http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/. This one is actually promoted by jQuery and it works ;)