views.py
from django.views.generic import ListView
from .models import SampleModel
class SampleListView(ListView):
model = SampleModel
def get_queryset(self):
return SampleModel.objects.order_by('?')[:5]
-- .order_by ('?')` `` Randomize the order of objects --
[: 5] `` `Slice from the beginning to the 5th ([0] ~ [4]) of the array
views.py
from django.views.generic import ListView
from .models import SampleModel
import random
class SampleListView(ListView):
model = SampleModel
def get_queryset(self):
pks = SampleModel.objects.values_list('pk', flat=True)
pks_list = list(pks)
pks_random = random.sample(pks_list, 5)
queryset = SampleModel.objects.filter(pk__in=pks_random)
return queryset
--.values_list ('pk', flat = True) `` `Get only the pk value of each object in the list -* If
flat = True is not specified, the tuple list "([], [],)" will be returned. --
list (pks) `Since a list of QuerySet is generated, convert it to a pure list. --``` random.sample (pks_list, 5) ``` Select 5 randomly from the acquired pk value list --``` .filter (pk__in = pks_random)
`Get an object with 5 randomly selected pk values
If you have a smarter way to write than the above two, please let us know in the comments.
Recommended Posts