0

I am running django raw sql. Lets say if it returns 250 records. I want sample the results based on the input percentage given by the user on the form (In template). How can we achieve this? I can get the input number given by the user using get method. After that how can I sample the records? Please help me

-Vikram

2
  • from random import sample, no? Commented May 13, 2011 at 9:31
  • I want to show the (sampling) percentage of results. let say my sql select statement retrieves 90 records, I need to get get only 50% records then what could be the query? Commented May 13, 2011 at 11:05

1 Answer 1

1

I don't know why you are doing raw sql but here's a way you could do it using Django queries...

def sample_results(request):
  try:
    perc = float(request.GET['percent'])
  except AttributeError:
    # Default to showing all records
    perc = 100

  # Decimal version of percent
  perc = perc / 100

  # get all objects in a random order
  results = SomeModel.objects.all().order_by("?")

  #determine how many to grab from the queryset
  num = results.count()
  grab = int(num * perc)

  # refine the results to the first however many we need
  results = results[:grab]

  return render_to_response("some/template.html", {"results": results}, context_instance=RequestContext(request))

Thus, if you had /some/url?percent=40 this would show 40% of all the objects of a model, randomized.

Sign up to request clarification or add additional context in comments.

3 Comments

Isn't there a command to dump a query's SQL? I usually do that from Django Debug Toolbar, so I don't know the command name offhand.
HI Brant, thanks for your answer, I have done in the same way by default as 100 if nothing is given by the user. But coded in a different way :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.