django generic.listview中的额外上下文

django generic.listview中的额外上下文,django,django-generic-views,Django,Django Generic Views,所以我有两个模型:汽车和图片。一辆车可能有多张图片 现在,我想使用列表视图显示所有汽车以及每辆汽车的一张图片,有人能告诉我怎么做吗? 下面是我的代码 # 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.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

您可以使用模板中的
Car.pictures.all
直接访问每个汽车对象的相关图片对象

def get_context_data(self,**kwargs):
    context = super(CarList,self).get_context_data(**kwargs)
    context['picture'] = Picture.objects.filter(your_condition)
    return context
所以你可以这样做

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

有关详细信息,请阅读。

列表视图有一个获取上下文数据的方法。您可以覆盖此选项,将额外的上下文发送到模板中

def get_context_data(self,**kwargs):
    context = super(CarList,self).get_context_data(**kwargs)
    context['picture'] = Picture.objects.filter(your_condition)
    return context
然后,在模板中,您可以根据需要访问
图片
对象


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

因为我想用queryset传递表单,下面的方法对我很有效

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()可以定义一个基本queryset,它将由super()中的get_context_data()实现。

它不应该是
car.picture\u set.all
?当您在外键中指定相关的\u名称时,您可以在反向关系中使用它。非常感谢!这就是相关名称的工作原理