Ali Raza Javeed
Ali Raza Javeed

Reputation: 155

delete record form intermediate table in many to many relations in django

I have two models such as clinic and doctor. I have a list of clinics which are associated with a specific doctor by this CBV

class DoctorDetailView(generic.DetailView):
model = Doctor
# slug = none
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['clinic_hospital_list'] = self.object.clinic_hospital.all()
    return context

I want other CBV which delete clinic that has association with doctor.

Upvotes: 2

Views: 128

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

We can make a DeleteView [Django-doc] that works on the "through model" between the doctor and the hospital:

from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy

class DoctorClinicDeleteView(generic.DeleteView):
    model = Doctor.clinic_hospital.through
    success_url = reverse_lazy('some_view')

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()
        return get_object_or_404(
            queryset,
            doctor_id=self.kwargs['doctor_id'],
            clinic_id=self.kwargs['clinic_id']
        )

and in the urls.py, you then make a path with:

# app/urls.py

from django.urls import path

urlpatterns = [
    path('<int:doctor_id>/<int:clinic_id>/delete', DoctorClinicDeleteView.as_view(), name='delete_doctor_clinic'),
    # …
]

Then you make a POST or DELETE request to the view for a given doctor_id and clinic_id to remove that relation.

Upvotes: 1

Related Questions