【问题标题】:How to retrieve max (pk) in python from a table database?如何从表数据库中检索python中的最大值(pk)?
【发布时间】:2015-08-28 06:13:47
【问题描述】:

好吧,这听起来可能很愚蠢,我对 django 和数据库很陌生。

我正在尝试通过模板从数据库中删除多个条目。

这是我的观点.py

def names(request):
    e = Clash.objects.all()
    for z in range(0 ,100): ##### need to change this 100 to max(pk)######
        if request.POST.get('check'+str(z), False):
            to_delete = Clash.objects.get(pk=z)
            print (to_delete)
            to_delete.delete()

    return render_to_response("names.html", locals() , context_instance = RequestContext(request))

Clash 是我的模型,这是我要从中删除的模板:

<form method='POST' action=''>
       {% csrf_token %}
    {% for l in e %}
    <p>{{l.name }}

    {{l.second_name}}</p>

    <input type='checkbox' id="check{{l.id}}" name="check{{l.id}}"/>

    {% endfor %}

    <br>
    <input type='submit' value='Delete Selected'/>

</form>

如何从表中检索最大 pk?并将其放在“100”的位置:
PS:我知道复选框的名称和 ID 相同(没关系)
PSS:这段代码有效,我可以删除多个条目,但这不是好的编程。我该如何改进它?

【问题讨论】:

    标签: python django sqlite checkbox


    【解决方案1】:

    Anentropic 指出了在 Python 中循环遍历事物的正确方法:即遍历列表本身,而不是数字范围。

    但是,这仍然非常低效。如果您的数据库中有一百万行,会发生什么?你真的根本不想迭代。相反,您只需要直接要求数据库删除您想要的行。

    在您的模板中,更改复选框,以便将所有值放在同一个参数中:

    <input type='checkbox' name="to_delete" value="{{l.id}}"/>
    

    现在在您看来,只需获取该值列表并将其删除:

    def names(request):
        to_delete = request.POST.getlist('to_delete')
        if to_delete:
            Clash.objects.filter(pk__in=to_delete).delete()
    
        return render_to_response("names.html", locals() , context_instance = RequestContext(request))
    

    【讨论】:

      【解决方案2】:

      你不要这样做:

      e = Clash.objects.all()
      for z in range(0 ,100): ##### need to change this 100 to max(pk)######
      

      相反,您可以直接遍历查询集:

      for obj in Clash.objects.all():
      

      这也意味着您也不需要在循环的每次迭代中执行此额外查询:

      to_delete = Clash.objects.get(pk=z)
      

      ...因为您已经从数据库加载了该对象,如obj

      所以你可以这样做:

      def names(request):
          for obj in Clash.objects.all():
              if request.POST.get('check'+str(obj.id), False):
                  print obj
                  obj.delete()
          return render_to_response("names.html", locals() , context_instance=RequestContext(request))
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        last_item_pk = Clash.objects.last().pk
        

        查看这里了解详情: https://docs.djangoproject.com/en/dev/ref/models/querysets/#last

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-17
          相关资源
          最近更新 更多