【问题标题】:Django get children of parent on parent detail pageDjango在父母详细信息页面上获取父母的孩子
【发布时间】:2021-03-12 21:58:10
【问题描述】:

我正在尝试访问模型的子代并在父代详细信息页面上列出它们。这是我的设置方式...

型号:

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)

观看次数:

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)

模板:

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

它不会抛出错误或任何东西,但不会显示任何内容。我已经导入并正确设置了所有内容,我想我只是缺少如何在我的视图中正确设置它。任何见解将不胜感激。

【问题讨论】:

    标签: python django view model


    【解决方案1】:

    您在 {{airport.title}} 中没有任何内容 如果你想获得目的地的标题,你可以这样做

    {{ airport.city.title }}
    

    【讨论】:

      【解决方案2】:

      如果你把过滤器放在下一行呢?

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

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

      【讨论】:

        【解决方案3】:

        您的Airport.objects.filter(city=destination.id)Airports 的Queryset,所以是一个集合。因此,您对其进行迭代。我还建议将变量重命名为airports,因为这暗示这是Airports 的集合,所以:

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

        然后使用:

        {% for airport in airports %}
            <h1>
                {{ airport.title }}
            </h1>
        {% endfor %}

        注意:通常最好使用get_object_or_404(…) [Django-doc], 然后直接使用.get(…) [Django-doc]。如果对象不存在, 例如,由于用户自己更改了 URL,get_object_or_404(…) 将导致返回 HTTP 404 Not Found 响应,而使用 .get(…) 将导致 HTTP 500 服务器错误

        【讨论】:

          猜你喜欢
          • 2015-04-24
          • 2015-08-30
          • 2018-01-29
          • 1970-01-01
          • 2013-06-04
          • 2021-11-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多