【问题标题】:extra context in django generic.listviewdjango generic.listview 中的额外上下文
【发布时间】:2015-06-18 08:25:47
【问题描述】:

所以我有两个模型:汽车和图片。一辆车可能有多张图片。

现在我想使用列表视图来显示所有汽车以及每辆汽车的一张图片,有人可以告诉我该怎么做吗? 下面是我的代码

# models.py
class Car(models.Model):
  name = models.CharField(max_length=100)
class Picture(models.Model):
  car = models.ForeignKey(Car,related_name='pictures')
  picture = models.ImageField()

# views.py
class CarList(ListView):
  model = Car

【问题讨论】:

    标签: django django-generic-views


    【解决方案1】:

    列表视图有一个方法get_context_data。您可以覆盖它以将额外的上下文发送到模板中。

    def get_context_data(self,**kwargs):
        context = super(CarList,self).get_context_data(**kwargs)
        context['picture'] = Picture.objects.filter(your_condition)
        return context
    

    然后,在您的模板中,您可以随意访问picture 对象。

    我想这应该可以解决你的问题。

    【讨论】:

    • 谢谢 :) 我在函数结束时缺少“返回上下文”。
    【解决方案2】:

    因为我想通过查询集传递表单,所以以下对我有用。

    def get_queryset(self):
        return Men.objects.filter(your condition)
    
    def get_context_data(self,**kwargs):
        context = super(Viewname,self).get_context_data(**kwargs)
        context['price_form']=PriceForm(self.request.GET or None)
        return context
    

    使用 get_queryset() 您可以定义一个基本查询集,该查询集将由 super() 中的 get_context_data() 实现。

    【讨论】:

      【解决方案3】:

      您可以通过在模板中使用car.pictures.all 直接访问每个Car 对象的相关Picture 对象。

      所以你可以做类似的事情,

      {% for car in objects %}
          {{ car.name }}
          {% if car.pictures.all %}<img src="{{ car.pictures.all.0.picture.url }}" />{%endif %}
      {% endfor %}
      

      欲了解更多信息,请阅读Related Objects

      【讨论】:

      • 不应该是car.picture_set.all吗?
      • 当您在外键中指定related_name 时,您将能够在反向关系中使用它。
      • 非常感谢!这就是相关名称的工作原理
      猜你喜欢
      • 2015-05-04
      • 2016-01-15
      • 2012-05-04
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多