1

I'm having trouble trying to wrap my head around this. many-to-one relationships are well documented, but I can't find an example on how to pass all of the relationships of a model.objects.all() lookup to context.

I'm trying to do something like

models.py

from django.db import models

class Image(models.Model):

    image_file = models.ImageField()
    imageset = models.ForeignKey(ImageSet)


class ImageSet(models.Model):
    title = models.CharField(max_length)

views.py

from django.shortcuts import render
from models import Image, ImageSet

def images(request):
    imagesets = ImageSet.objects.all()
    return render(request, 'template.html', {'imagesets': imagesets})

template.html

{% for imageset in imagesets %}
    {{ imageset.title }}
    {% for image in imageset.images  %}
        <img src="{{image.image_file.url}}" alt="">
    {% endfor %}
{% endfor %}

I've tried imagesets = ImageSet.objects.all().prefetch_related() but it only seems to work for ManyToMany relationships.

4

2 回答 2

1

Given an instance of the ImageSet model, you can access the related images with...

images = my_imageset.image_set.all()

...so you can just change the template to...

{% for imageset in imagesets %}
    {{ imageset.title }}
    {% for image in imageset.image_set.all  %}
        <img src="{{image.image_file.url}}" alt="">
    {% endfor %}
{% endfor %}

See the Django documentation on Related objects for more information.

于 2013-06-13T17:48:12.580 回答
0

views.py will be like this:-

from django.shortcuts import render
from models import Image, ImageSet

def images(request):
    t=get_template("template.html")
    imagesets = ImageSet.objects.all()
    image = Image.objects.all()
    html=t.render(Context({'imagesets':imagesets,'image':image}))
    return HttpResponse(html)

In template.html:

{% for image in imageset.images  %} line will not work as imageset.image does not
exist because Imageset model having only one field title so you cat't access that.
if you   want to access image field of Image model then from views.py you have to send
that object also.
and <img src="{{image.url}}" alt=""> will not work. where is your url field??

---------thanks-------

于 2013-06-13T17:41:51.463 回答