django 选择3个随机项目并排除已选择的项目

agxfikkp  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(103)

我尝试在模板中显示三种随机饮料,从饮料数据库中选择。我目前正在进行随机选择,但也注意到有可能出现两次饮料。如何防止这种情况发生?有更聪明的方法吗?

import random
def testview(request):

   
    drink1 = random.choice(DrinkRecipe.objects.all())
    drink2 = random.choice(DrinkRecipe.objects.all())
    drink3 = random.choice(DrinkRecipe.objects.all())

    context ={
            'drink1' : drink1,
            'drink2' : drink2,
            'drink3' : drink3,
        }

    return render(request,'drinks/test.html', context=context)
a5g8bdjr

a5g8bdjr1#

我会用途:

drinks = DrinkRecipe.objects.all().order_by("?")[:3]
context = {"drinks": drinks}

相关问题