0

How do i delete multiple record in django?

    idproduct = request.POST.get('relatedid')
    products = GroupAndProduct.objects.filter(id=idproduct)
    record=GroupAndProduct.objects.get(id=products)
    record.delete()

enter image description here

3
  • first get object list using filter then use delete. ex: GroupAndProduct.objects.filter(id=idproduct).delete() Commented Aug 15, 2020 at 11:44
  • please see my updated question Commented Aug 15, 2020 at 11:47
  • if 2nd line have multiple objects then just use products.delete() instead of line 4 and line 5 Commented Aug 15, 2020 at 11:52

1 Answer 1

2

The line record = GroupAndProduct.objects.get(id=products) is responsible for this error. Because get method requires exact lookup (for instance pk=1) but you send a queryset to another queryset's filter to get an object. First of all make sure that you know the type of idproduct = request.POST.get('relatedid'). If the idproduct is a list of ids, then you should do something like:

GroupAndProduct.objects.filter(id__in=idproduct).delete()

to delete multiple GroupAndProduct instances. But if idproduct is a number (or string type of a number) you should use:

GroupAndProduct.objects.filter(id=idproduct).delete()

So I think changing your codes to something like:

idproduct = request.POST.get('relatedid')
GroupAndProduct.objects.filter(id__in=idproduct).delete() # or .filter(id=idproduct).delete()

will solve your problem. Both of the solutions will delete all records that satisfies the queryset filter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.