class Album(models.Model):
title = models.CharField(max_length=250)
date = models.DateTimeField(default=datetime.now)
image = models.ImageField(upload_to='photos')
class Photo(models.Model):
title = models.CharField(max_length=250,
help_text='Maximum 250 characters.', blank=True)
slug = models.SlugField(unique = True,
help_text='Suggested value automatically generated from title. Must be unique.', null=True)
caption = models.TextField(blank=True, max_length=250,
help_text='An optional summary.')
date = models.DateTimeField(default=datetime.now)
image = models.ImageField(upload_to='photos',
help_text='Maximum resolution 800x600. Larger images will be resized.')
album = models.ForeignKey(Album)
class Meta:
ordering = ['-date']
def __unicode__(self):
return self.title
我在models.py中有这样的东西,我想在视图中编写一个函数,选择与所请求的相册相关的所有照片并将其返回到相应的html页面
def album_list(request):
album_choice = Album.objects.all()
return render(request, "talks/gallery.html", {'album_choice':album_choice})
def photo_list(request):
queryset = Photo.objects.filter
context = {
"photos" : queryset,
}
return render(request, "talks/", context)
此外,我在views.py中也有此功能,因此假设用户点击特定类别,然后打开它以显示与其相关的图像。如何检索此信息?
答案 0 :(得分:0)
class Album(models.Model):
title = models.CharField(max_length=250)
date = models.DateTimeField(default=datetime.now)
image = models.ImageField(upload_to='photos')
def get_photos(self):
return Photo.objects.filter(album=self)
class Photo(models.Model):
title = models.CharField(max_length=250,
help_text='Maximum 250 characters.', blank=True)
slug = models.SlugField(unique = True,
help_text='Suggested value automatically generated from title. Must be unique.', null=True)
caption = models.TextField(blank=True, max_length=250,
help_text='An optional summary.')
date = models.DateTimeField(default=datetime.now)
image = models.ImageField(upload_to='photos',
help_text='Maximum resolution 800x600. Larger images will be resized.')
album = models.ForeignKey(Album)
class Meta:
ordering = ['-date']
def __unicode__(self):
return self.title
Views.py
def album_list(request):
#view for all albums
album_choice = Album.objects.all()
return render(request, "talks/gallery.html", {'album_choice':album_choice})
def photo_list(request, pk=None):
#view for particular album view
album = get_object_or_404(Album, pk=pk)
queryset = Photo.objects.filter
context = {
"album" : album,
}
return render(request, "talks/", context)
#in your template for a particular album view
{% for photo in album.get_photos %}
<img src="{{ photo.image.url }}" />
{% endfor %}
在所有相册视图的模板中,为每张相册加载相关照片
{% for album in album_choice %}
{% for photo in album.get_photos %}
<img src="{{ photo.image.url }}" />
{% endfor %}
{% endfor %}