首页 > 解决方案 > 如何在跟踪以前的项目的同时从 Django 的列表中返回一个新的非重复项目?

问题描述

我正在开发一个应用程序,用户可以在其中选择一个类别,这将返回该类别的随机选择。我试图实现的主要功能是一旦选择了一个项目,它就不能再在会话中随机选择。

例如,我们有3 类照片:风景、城市和人像,每类有5 张照片。用户选择城市,然后被重定向到带有来自城市类别的随机照片的详细信息页面。他可以刷新页面或单击按钮从该类别中获取新照片。当该类别没有新照片时,他会被重定向回家。

我可以通过将查询集转换为列表来从所选类别中获取我的随机项目,但数据不会持久。每次刷新时,我都会重置列表,因此之前选择的照片可以再次出现,忽略了我在选择后从列表中删除了该项目的事实。

这是views.py,其功能负责:

def randomPhoto(request, pk, **kwargs):

    # queryset to get all photos from selected category
    gallery = list(Photos.objects.filter(id=pk)
    .values_list("partof__category", flat=True))

    # select random photo from list
    last = len(gallery) -1
    randomInt = random.randint(0, last)
    randomPic = gallery[randomInt]

    gallery.remove(randomPic)

    if len(gallery) == 0:
        return render(request, 'gallery/category_select.html')

        photoDetails = {
        'category' : Category.objects.get(id=pk),
        'author' : Author.objects.get(tookin__category=randomPic),
        'uploadedPhoto' : 'http://localhost:8000/media/' + 
    str(Photo.objects.get(category=randomPic).photoUpload),
        'randomPic' : randomPic,
        }

        return render(request, 'gallery/random_photo.html', {'photoDetails': photoDetails})

我正在寻找的功能是(每个数字都是列表中的一个对象/项目):

我相信我的问题在于必须配置会话或 cookie 以使数据在匿名会话中持续存在。最终我将添加一个用户模块,这样每个用户都会保存他们的浏览历史记录,但现在我希望它像匿名用户一样工作。

我尝试添加SESSION_SAVE_EVERY_REQUEST = Truesettings.py放置request.session.modified = True在我的 中views.py,但我怀疑我是否正确实施它们。我已经阅读了一些关于会话和 cookie 的 SO 问题,但找不到可以解决我的问题的内容。Django Sessions Doc看起来很有趣,但势不可挡。我不确定从哪里开始尝试将会话方面连接在一起。

我想知道是否有一种简单/Pythonic 的方式来实现让我的网络应用程序从列表中给我一个非重复项,直到会话中没有任何内容。

标签: djangosessionrandomdjango-querysetdata-persistence

解决方案


您的问题是您的变量没有从一个请求转移到下一个请求。最好的方法是使用request.session = ...设置一个变量,然后稍后检查它并执行操作。这是一个示例,您可以对其进行扩展以使其符合您的喜好:

import random
from django.shortcuts import redirect

class TestView(View):
    def get(self, request, *args, **kwargs):

        gallery = request.session.get('gallery', None)
        if (type(gallery) is list) and (len(gallery) == 0):  # When list is empty, clear session & then redirect
            del request.session['gallery']
            request.session.modified = True
            return redirect('<your_redirect_url>')
        if gallery is None:  # If first visit to page, create gallery list
            gallery = list(models.Photos.objects.all().values_list("partof__category", flat=True))

        # select random photo from list
        last = len(gallery) -1
        randomInt = random.randint(0, last)
        randomPic = gallery[randomInt]
        gallery.remove(randomPic)

        request.session['gallery'] = gallery

        return render(request, 'test.html', {})

推荐阅读