Django photologue images and queryset



我已经在我的项目中添加了摄影,因为它完成了我自己想要实现的99%的事情。

现在我需要将上传的图像和画廊中的图像连接到我的帖子。这就是为什么我在照片模型中添加了一个 ManyToMany 字段

的原因
Class ImageModel(models.Model):
post_images =  models.ManyToManyField(Post, blank=True)

并将对图库模型执行相同的操作

class Gallery(models.Model):
post_gallery =  models.ManyToManyField(Post, blank=True)

现在我的想法是能够在我的帖子中添加画廊和/或特定图像。这两个选项都应该可用。

我想要的查询集是获取附加到帖子的所有单个图像,如果附加了图库,则还要获取图库中的所有图像。然后将它们传递并呈现到某种图库中的页面(滑块、轮播或其他内容(。 我希望能够通过一个 for 循环将它们放入模板中,所以我认为查询集必须是一个。

我有一个呈现特定页面类型的视图,我不知道我是否应该在此函数中包含查询集和上下文,或者为图像创建一个新查询集和上下文。以及如何做到这一点。

def post(request, slug):
post = get_object_or_404(Post, post_slug=slug)
context = {
'post': post,
}
return render(request, 'project_name/post.html', context)

我希望我已经解释了我想做什么。 Django 对我来说是新的,查询集仍然有点复杂。

您不应该尝试从帖子中添加画廊到帖子吗?

from photologue.models import Gallery
class Post(models.Model):
gallery = models.ManyToManyField(Gallery, blank=True )

#Edit ___ @TwinDewey 在这种情况下,您需要在视图中进行查询,以便在显示帖子详细信息时获取库。

galleries = gallery.posts.all() 
gal = [] 
for excercise in excercises: 
gal.append(Gallery.objects.filter(gallery__name=self.post.title)) 

或者,您可以进行查询并将其与 Post 上下文合并

使用
from itertools import chain 
list(chain(post_context,Gallery.objects.filter(gallery__name=self.post.title))) 

那是画廊。帖子会有另一个查询。

您可以使用联合将绑定到帖子本身和图库内的照片分组。诀窍是获得正确的模型,使它们是相同的对象:

from django.db import models
from photologue.models import Gallery, Photo

class Post(models.Model):
title = models.CharField(max_length=100)
published_at = models.DateTimeField(blank=True, null=True)
text = models.TextField()
photos = models.ManyToManyField(Photo, related_name='posts')
galleries = models.ManyToManyField(Gallery, related_name='posts')
@property
def all_images(self):
# Create a number of querysets that have photos from selected galleries
# ..note:
#   .only() is used to trim down on the fields fetched from the database.
#   .prefetch_related() is used to eliminate extra queries during iteration
qs = []
for gallery in self.galleries.prefetch_related('photos').only('photos'):  # type: Gallery
qs.append(gallery.photos.only('image', 'title'))
return self.photos.only('image', 'title').union(*qs)      

现在您可以在模板中使用它,如下所示:

{% for photo in post.all_images %}
<img src="{{ photo.image.url }}" alt="{{ photo.title }}" />
{% endfor %}

最新更新