Home > OS >  Can't display foreign key related object in Django DetailView
Can't display foreign key related object in Django DetailView

Time:10-12

I've got a booking class which is related to Customer and Barber models. I can display all bookings using the detail view, however, can't figure out how to display a booking/bookings that a specific barber has. Basically, I want to get a booking or multiple bookings of a barber based on the ID given to the url.

Here is my model:

    customer_id = models.ForeignKey(User, on_delete = models.CASCADE,)
    barber_id = models.ForeignKey(Barber, on_delete = models.CASCADE)
    timeslot = models.DateTimeField('appointment')

    def __str__(self):
        return f"{self.customer_id} {self.barber_id} {self.timeslot}"
    
    def get_absolute_url(self):
        return reverse("model_detail", kwargs={"pk": self.pk})

My view:

class GetBarberBooking(DetailView):
   model = Booking
   template_name = "barber_booking.html"

   def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       context['barber'] = Booking.objects.filter(
           id=self.kwargs.get('<str:pk'))
       return context 

My url path:

path('barber-booking/<str:pk>/', views.GetBarberBooking.as_view(), name='barber-booking'),

CodePudding user response:

You can remove this piece of code:

context['barber'] = Booking.objects.filter(
           id=self.kwargs.get('<str:pk'))

And in template just use:

{{ object.barber_id }}

And show all the booking for barber:

{{ object.barber_id.booking_set.all }}

It will show all the the barber. This works because of FK relation between Booking and Barber model. More information can be found in Django documentation. For reverse relation (Many to one), please check this documentation.

FYI, you do not need to create a field name suffix with _id, because Django creates that automatically for you.

Also, if you want to query a Barber, then you should use Barber as the model in the DetailView. Then you can use a similar query mentioned above:

# view
class GetBarberBooking(DetailView):
   model = Barber

# template
{{ object.booking_set.all }}
  • Related