Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – List Filtering using a ForeignKey within a ForeignKey

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading