Django get a random object from database or Elasticsearch

random.sample(list(, k=count)

With conversion function one can select random object from a selection number.

For example usage in an view. We first search in Elastic and then we return only random objects from selection.



def ads(request, template_name="job/job_redirect.html"):
    """
    Get firest job by sourece and keyword and redirect
    """
    try:
        keyword = request.GET.get("k", "administratief")
        source = request.GET.get("s", "stepstone.be")
    except (TypeError, ValueError):
        raise Http404("Not a valid number for page.")

    sqs = random.sample(list(SearchQuerySet().using('default').filter(source=source).filter(content=AutoQuery(keyword))), k=1)
    job = sqs[0].object

    try:
        apply_click = ApplicationClicksCount(job_id=job.id, job_title=job.title, source=job.source, ip=get_ip(request), user_agent=request.META["HTTP_USER_AGENT"])
        apply_click.save()
    except:
        pass

    data = {
        'job': job,
        'site': Site.objects.get_current(),
    }
    url = reverse('viewjob_pk', kwargs={'pk': job.id, 'slug': job.slug})
    if job.url:
        url = job.url
    return redirect(url, permanent=True)

Comments