在django中采样mysql结果

发布于 2024-11-07 04:14:08 字数 141 浏览 3 评论 0原文

我正在运行 django raw sql。假设它返回 250 条记录。我想根据用户在表单上给出的输入百分比(在模板中)对结果进行采样。我们怎样才能做到这一点?我可以使用 get 方法获取用户给出的输入数字。之后我如何对记录进行采样?请帮助我

-维克拉姆

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_畞蕅 2024-11-14 04:14:08

我不知道你为什么要执行原始 sql,但这里有一种方法可以使用 Django 查询来完成......

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))

因此,如果你有 /some/url?percent=40 这将显示模型所有对象的 40% ,随机化。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文