使用Django ----如果有超过1条记录然后显示它,如果只有1条记录,那么我将其删除

时间:2015-07-05 19:41:01

标签: python django

我的问题是这个代码显示记录是否有1条记录或多条...但我想删除是否有1条记录.... 任何关于良好代码编写的建议都是有责任的......

这是我的观点

def delete(请求):     form = SearchForm(request.POST)

searched_data = Information.objects.filter(name="full_name").count()

d_data = None

if form.is_valid():
    if (searched_data == 1):
        d_data = Information.objects.filter(name= form.cleaned_data.get('full_name')).delete()
    else:
        d_data = Information.objects.filter(name=form.cleaned_data.get('full_name'))


context = {
    'form': form,
    'd_data': d_data,

}

return render(request, 'delete.html', context)

1 个答案:

答案 0 :(得分:1)

除非表格有效,否则我不会做任何事情:

if form.is_valid():
    d_data = Information.objects.filter(name=form.cleaned_data.get('full_name'))

    if len(d_data) == 1:
        d_data.delete()
        d_data = None
else:
    d_data = None

context = {
    'form': form,
    'd_data': d_data,
}

return render(request, 'delete.html', context)

注意:删除后,我将d_data设置为None

要使用d_data.count()len(d_data),请参阅this