Django随机对象并在模板中使用

时间:2018-07-28 08:25:15

标签: django django-class-based-views

首先,我是Django的新手。我的第一个项目是电影网络应用程序,其模型如下:

class Movie(models.Model):
### movie database ###

def __str__(self):
    return self.name

def get_random(self):
    max_id = Movie.objects.all().aggregate(max_id=Max('id'))['max_id']

    while True:
        pk = random.randint(1, max_id)
        movie = Movie.objects.filter(pk=pk).first()
        if movie:
            return movie

此“ get_random”函数仅给我1个回报。我可以得到更多,比方说10吗?

我在“ movies_index”模板中使用了此模型。 :

{% for movie in movies %}
<a href="{% url 'movies_detail' movie.get_random.pk %}">
<img src="{{ movie.get_random.poster }}" class="img-fluid">
{% endfor %}

网页可以显示带有超链接的电影海报。但是当我单击时,它会转到另一部电影。是的,因为我做了两次“随机”测试,所以得到了2种不同的结果。

我的问题是:如何选择一组随机数并在场景中使用一致性?

顺便说一句,我正在使用CBV,如下所示:

class MoviesIndex(ListView):
    model = Movie
    context_object_name = 'movies'
    template_name = 'movies/movies_index.html'

1 个答案:

答案 0 :(得分:0)

如果您只想始终以随机顺序列出电影对象,则只需在检索查询集时使用.order_by('?')

重写ListView的get_queryset方法

class MoviesIndex(ListView):
    model = Movie
    context_object_name = 'movies'
    template_name = 'movies/movies_index.html'

    def get_queryset(self):
       return Movie.objects.order_by('?')

并在模板中删除get_random

{% for movie in movies %}
   <a href="{% url 'movies_detail' movie.pk %}">
   <img src="{{ movie.poster }}" class="img-fluid">
{% endfor %}

或者,如果您仍然想get_random,请列出movie对象的所有ID

movie_pks = list(Movie.objects.values_list('id', flat=True))

,然后使用random.choice选择一个pk

import random
print(random.choice(movie_pks))
  

注意:在您的情况下,请勿使用random.randint,因为如果   的电影被删除,然后将失败

另外,从while True:方法中删除get_random,因为您将始终获得电影对象,所以不需要它

@property
def get_random(self):
    movie_pks = list(Movie.objects.values_list('id', flat=True))
    pk = random.choice(movie_pks)
    movie = Movie.objects.get(pk=pk)
    return movie

不要在模板中调用get_random两次,请使用with

{% with rand_movie=movie.get_random %}
    <a href="{% url 'movies_detail' rand_movie.pk %}">
    <img src="{{ rand_movie.poster }}" class="img-fluid">
{% endwith %}