[PYTHON] How to get multiple model objects randomly in Django

Development environment

The easiest way to write

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

A little long writing

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

Finally

If you have a smarter way to write than the above two, please let us know in the comments.

Recommended Posts

How to get multiple model objects randomly in Django
How to reflect CSS in Django
How to get started with Django
How to delete expired sessions in Django
How to get a stacktrace in python
How to do Server-Sent Events in Django
How to convert DateTimeField format in Django
How to get a namespaced view name from a URL (path_info) in Django
Dynamically add fields to Form objects in Django
How to implement Rails helper-like functionality in Django
How to get results from id in Celery
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
[Django] How to get data by specifying SQL.
How to get help in an interactive shell
How to get the files in the [Python] folder
How to create a Rest Api in Django
Model changes in Django
How to get people to try out django rest framework features in one file
How to improve model metric monitoring in Amazon SageMaker
How to get the variable name itself in python
How to get the number of digits in Python
How to write string concatenation in multiple lines in Python
How to display multiple images of galaxies in tiles
How to use bootstrap in Django generic class view
How to upload files in Django generic class view
How to use the model learned in Lobe in Python
How to use Decorator in Django and how to make it
How to retrieve multiple arrays using slice in python.
How to reference static files in a Django project
How to use Spacy Japanese model in Google Colaboratory
How to get RGB and HSV histograms in OpenCV
How to use fixture in Django to populate sample data associated with a user model
How to develop in Python
How to write custom validations in the Django REST Framework
How to embed multiple embeds in one message with Discord.py
How to adapt multiple machine learning libraries in one shot
How to get rid of server custom emoji in message.content
[Go language] How to get terminal input in real time
How to slice a block multiple array from a multiple array in Python
How to use Laravel-like ORM / query builder Orator in Django
How to check ORM behavior in one file with django
How to update user information when logging in to Django RemoteUserMiddleware
How to define multiple variables in a python for statement
[Django] How to give input values in advance with ModelForm
I tried "How to get a method decorated in Python"
How to generate a query using the IN operator in Django
How to get Instruction Pointer (= program counter) in Linux kernel
How to get the last (last) value in a list in Python
How to get all the keys and values in the dictionary
How to get a list of built-in exceptions in python
[TF] How to load / save Model and Parameter in Keras
In Django, how to abbreviate the long displayed string as ....
How to get an overview of your data in Pandas
[Shell] How to get the remote default branch in Git
How to get a quadratic array of squares in a spiral!
I wanted to delete multiple objects in s3 with boto3
How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django
[Python] How to do PCA in Python
How to handle session in SQLAlchemy
How to handle multiple versions of CUDA in the same environment