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
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.
精彩评论