Reputation: 187
I am trying to delete an Item in the QuerySet by Index. I am able to display the items of the QuerySet using print q_set[code_id - 1]
but can not delete it using del q_set[code_id - 1]
. I want to permanently delete the item and not filter excluding that item.
I am getting this error:
TypeError at /lessons/customcode/5/delete
'QuerySet' object doesn't support item deletion
views.py
...
def customcode_view(request):
global q_set
try:
u = User.objects.get(username=request.user)
except:
return render(request,"login_required.html",{})
q_set = customcode.objects.filter(user=u)
if request.method == "POST":
form = CustomcodeForm(request.POST)
if form.is_valid():
cc = form.save(commit=False)
cc.user = u
cc.save()
return HttpResponseRedirect('#BOTTOM')
else:
form = CustomcodeForm()
return render(request, "customcode.html" , {'q_set':q_set,'form':form,})
def deletecode(request,code_id):
code_id = int(code_id)
del q_set[code_id - 1] #this is the problem
return redirect('customcode_view')
...
models.py
...
class customcode(models.Model):
user = models.ForeignKey(User)
name = models.CharField(blank=False,max_length=250)
sourcecode = models.TextField(blank=False)
def __unicode__(self):
return self.name
...
Upvotes: 0
Views: 3789
Reputation: 11
first convert queryset to list if you want to use as a list
q_set_list=list(q_set)
Upvotes: 0
Reputation: 11
If you just want to get rid of the entry in your list but not of the row in your database try the following:
help = q_set[:]
q_set = q_set[:code_id - 1]
q_set.append(help[code_id:])
Upvotes: 1
Reputation: 2536
To permanently get rid of the entry, you don't want to remove the item from the queryset (which is just a volatile view onto your data), but delete the row from the database:
q_set[code_id - 1].delete()
Hth dtk
Upvotes: 3