Home > OS >  Django - List Filtering using a ForeignKey within a ForeignKey
Django - List Filtering using a ForeignKey within a ForeignKey

Time:04-08

I can filter the list of Bookings from "housing" using the "Housing" ForeignKey

But I need to do it based on the h_type which uses the "HousingType" ForeignKey

I am not sure of the correct terminology here but I think I am trying to use a ForeignKey within a ForeignKey, not sure how to accomplish this within the view.

models.py

class HousingType(models.Model):

    name = models.CharField(max_length=254)
    friendly_name = models.CharField(max_length=254, null=True, blank=True)

class Housing(models.Model):

    h_type = models.ForeignKey('HousingType', null=True, blank=True, on_delete=models.SET_NULL)

class Booking(models.Model):

    housing = models.ForeignKey('Housing', null=True, blank=True, on_delete=models.SET_NULL)

views.py

def view_bookings(request):

    housing = Housing.objects.all()
    bookings = Booking.objects.all()

    if request.GET:
        if 'housing_type' in request.GET:
            h_types = request.GET['housing_type'].split(',')
            bookings = bookings.filter(housing_type__name__in=h_types)
            h_types = HousingType.objects.filter(name__in=h_types)

html template

<a href="{% url 'view_bookings' %}?housing_type=apartments">Apartments</a>

CodePudding user response:

You can .filter(…) [Django-doc] with:

Booking.objects.filter(housing__h_type__name__in=h_types)

or if you use the friendly_name:

Booking.objects.filter(housing__h_type__friendly_name__in=h_types)
  • Related