I am building a website in which I want the user to make a wish first, and then select somebody else's wish and sketch it.
When the user comes to the part where he has to select a wish, I want to give him a choice from three wishes to choose from. To make the basic random method efficient and make sure that the wishes that are asked first get a better chance, this is what I want to do:
Get the first 10 wishes from the database which have the desired attributes (is_live=True and locked=False), and then use order_by['?'] to randomize the order. Then I just want to display the top three wishes from these 10.
Here is my code:
Form:
class GetWishForm(forms.ModelForm):
wish = forms.ModelChoiceField(queryset='', initial=0)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(GetWishForm, self).__init__(*args, **kwargs)
query1 = Wish.objects.exclude(wisher=self.request.user).filter(pk__in=Wish.objects.filter(is_live=True, locked=False)[:10].values_list('pk')).order_by('?')
self.fields["wish"].queryset = query1
class Meta:
model = Sketch
fields = ('wish',)
Snippet from Views:
elif 'submit_get_wish' in which_submit:
get_wish_form = GetWishForm(request.POST, request=request)
if get_wish_form.is_valid():
to_sketch = get_wish_form.save(commit=False)
to_sketch.sketcher = request.user
to_sketch.save()
Wish.objects.filter(pk=request.POST['wish']).update(locked=True, sketcher=request.user)
curr_user = UserProfile.objects.get(user=request.user)
curr_user.progress = 3
curr_user.save()
return HttpResponseRedirect(reverse('start'))
else:
print get_wish_form.errors
messages.error(request, 'Error, try again', fail_silently=True)
return HttpResponseRedirect(reverse('start'))
As you will see, I am getting the 10 top wishes ordered randomly. How do I get three from that queryset?
I tried slicing but then I get error when the user submits.
I will also want the user to get only the three wishes that got generated once, and not refresh and get three new random wishes. Beats the purpose of giving him a choice. But this can be done later.
Aucun commentaire:
Enregistrer un commentaire