如何将一对多关系传递给objects.all()查找为可迭代的上下文

时间:2013-06-13 17:33:29

标签: python django django-models django-views django-queryset

我在试图绕过这个问题时遇到了麻烦。多对一关系有详细记录,但我找不到一个关于如何将model.objects.all()查找的所有关系传递给上下文的示例。

我正在尝试做类似

的事情

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 %}

我尝试过imagesets = ImageSet.objects.all().prefetch_related(),但它似乎只适用于ManyToMany关系。

2 个答案:

答案 0 :(得分:1)

给定ImageSet模型的实例,您可以使用...

访问相关图像
images = my_imageset.image_set.all()

...所以您只需将模板更改为...

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

有关详细信息,请参阅Related objects上的Django文档。

答案 1 :(得分:0)

views.py将是这样的: -

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)

在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??

---------感谢-------