简体   繁体   中英

Django get children of parent on parent detail page

I'm trying to get access to the children of a model and list them on the parents details page. Here is how I have it set up...

Models:

class Destination(models.Model):
      title = models.CharField( null=True, max_length=60, blank=True)
      featuredimage = models.ImageField(null=True, blank=True, upload_to ='media/')
      location = PlainLocationField(based_fields=['title'], zoom=7, null=True, blank=True)

class Airport(models.Model):
      title = models.CharField( null=True, max_length=60, blank=True)
      city = models.ForeignKey(Destination, null=True, blank=True, on_delete=models.SET_NULL)

Views:

def destination_detail(request, slug):
    destination = Destination.objects.get(slug=slug)
    context = {
    'destination': destination,
    'airport': Airport.objects.filter(city = destination.id),
    }
    return render(request,"destination/detail.html",context)

Template:

<h1>
    {{ airport.title }}
</h1>

It doesn't throw an error or anything but nothing is displayed. I have everything imported and set up correctly, I think I'm just missing on how to properly set it up in my views. Any insight would be greatly appreciated.

Your Airport.objects.filter(city=destination.id) is a Queryset of Airport s, so a collection . You thus iterate over it. I would also advise to rename the variable to airports , since that hints that this is a collection of Airport s, so:

from django.shortcuts import get_object_or_404

def destination_detail(request, slug):
    destination = get_object_or_404(Destination, slug=slug)
    context = {
        'destination': destination,
        : Airport.objects.filter(city=destination)
    }
    return render(request, 'destination/detail.html', context)

and then render this with:

{%  %}
    <h1>
        {{ airport.title }}
    </h1>
{% endfor %}

Note : It is often better to use get_object_or_404(…) [Django-doc] , then to use.get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error .

What if you put in the filter the next line?

context = {
    'destination': destination,
    'airport': Airport.objects.filter(city_id=destination.id)[0]
}

or

context = {
    'destination': destination,
    'airport': Airport.objects.get(city_id=destination.id)
}

you don't have anything in {{airport.title}} if you want to get the title of the destination you can do

{{ airport.city.title }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM