Search code examples
djangodjango-generic-views

extra context in django generic.listview


So I have two models: Car and Picture. a car may have multiple pictures.

Now I want to use a list view to display all the cars along with one picture for each car, can someone tell me how can I do that? Below is my code

# 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

Solution

  • You can directly access the related Picture objects to each Car object by using car.pictures.all in your template.

    So you could do something like,

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

    For more info, read up on Related Objects.