Reputation: 1577
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
Upvotes: 8
Views: 14383
Reputation: 3386
List view has a method get_context_data. You can override this to send extra context into the template.
def get_context_data(self,**kwargs):
context = super(CarList,self).get_context_data(**kwargs)
context['picture'] = Picture.objects.filter(your_condition)
return context
Then, in your template you can access picture
object as you wish.
I guess this should solve your problem.
Upvotes: 23
Reputation: 31
As I wanted to pass forms with queryset, following worked for me.
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
Using get_queryset() you can define a base queryset that will be implemented by get_context_data() in super().
Upvotes: 3
Reputation: 4043
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.
Upvotes: 3