[Django]-Delete identical row in many MySQL tables

2πŸ‘

βœ…

Here is the solution after we talked πŸ™‚

@login_required
def Identity_Deleting(request) :

    query_number = request.GET.get('q6')

    if query_number :
        query_number_list = Individu.objects.filter(NumeroIdentification__iexact=query_number)    
    else :
        query_number_list = Individu.objects.none()

    instance = query_number_list.first()
    form = IndividuFormulaire(request.POST or None, instance = query_number_list.first())

    if "Delete" in request.POST :
        ids_to_delete = list(query_number_list.values_list('id', flat=True))
        for element in settings.BDD :
            form = Individu.objects.using(element).filter(pk__in=ids_to_delete).delete() 

        return HttpResponseRedirect(reverse('Home'))

There is two importants things:

  • The first queryset query_number_list result should be saved in a list in order to be used later
  • .using() should be used before .delete()
πŸ‘€Thom

1πŸ‘

It is a mysql restriction, see this answer.

Try to modify your request by forcing evaluation of queryset instead of using a subquery using list:

 Individu.objects.filter(pk__in=list(query_number_list.values_list('id', flat=True))).delete().using(element)

or if there is always only 1 Individu you may want something like:

@login_required
def Identity_Deleting(request) :

    query_number = request.GET.get('q6')

    if query_number :
        individu = Individu.objects.filter(NumeroIdentification__iexact=query_number).first()
    else :
        individu = None

    form = IndividuFormulaire(request.POST or None, instance = individu)

    if "Delete" in request.POST:
        if individu is not None:
            for element in settings.BDD :
                Individu.objects.filter(pk=individu.pk).delete().using(element)

        return HttpResponseRedirect(reverse('Home'))

Leave a comment