I am writing an application that allows people to compare different pairs of hashtags.
Model:
class Competitors(models.Model): tag1 = models.ForeignKey('Hashtag', related_name='+') tag2 = models.ForeignKey('Hashtag', related_name='+') votes = models.PositiveIntegerField(default=0, null=False)
View:
def compare_hashes(request, i=None): i = i or 0 try: competitors = Competitors.objects.order_by('?')[i] except IndexError: return render(request, 'hash_to_hash.html', {'tag1': '', 'tag2': '', i: 0, 'done': True}) if request.method == 'POST': form = CompetitorForm(request.POST) if form.is_valid(): if "yes" in request.POST: competitors.votes += 1 competitors.save() i += 1 return render(request, 'hash_to_hash.html', {'tag1': competitors.tag1, 'tag2': competitors.tag2, i: i, 'done': False}) else: return render(request, 'hash_to_hash.html', {'tag1': competitors.tag1, 'tag2': competitors.tag2, i: i, 'done': False})
I want each visitor to randomize the ordering of competitors' objects, and then iterate over this randomized list.
Questions:
- What is the best way to randomize things besides o
bjects.order_by('?') ? I use MySQL and I saw some things here about how order_by('?') + MySQL = SLOOOOOOOW. Several suggestions were suggested, and I could easily implement something (I thought something like random.shuffle(Competitors.objects.all()) ), but I'm not sure where I would put it, which leads me to my second question ... - How can I make sure that randomization only happens once? I do not want to miss people, forcing them to review the same pairs again and again, and I do not want to discard my results when several pairs accidentally appear more than once. I want everyone to see the same list, only in different orders.
I suspect that the answer lies in the manager class, but, really, it all comes down to my lack of knowledge of what Django causes when.
(I also have a problem where the results do not seem to be stored in my db, but this is a problem that may be more easily resolved).
source share