[Fixed]-Django for loop random order determine

1👍

I would create a model manager to do your initial filtering, and then randomize the order of the objects in your view. You want to try to take a “fat” model, “thin” view approach. The more you can do in your model, the easier changes will be down the road. For example,

models.py:

class FooManager(models.Manager):
    def get_titles(self):
        return super(FooManager, self).get_queryset.order_by('title')

class Foo(models.Model):
    title = models.CharField(max_length=120)

    objects = FooManager()

    def __unicode__(self):
        return self.title

views.py:

def view(request):
    get_titles = Foo.objects.get_titles()[:10]
    titles = list(get_titles)
    random.shuffle(titles)

    context = {
        'titles': titles
    }
    return render(request, 'template.html', context)

Your templates become a lot easier, too.

html:

{% for t in titles %}
    {{ t.title }}
{% endfor %}

I hope that helps! Good luck!

👤jape

Leave a comment