Django randomly extracts data from a specified table in the database

created at 07-17-2021 views: 2

Django randomly extracts data from the specified table in the specified database

method 1: use order_by

Article.objects.all().order_by('?')[:10]

This method is slow when the amount of data in the data table is too large, and when the amount of data in the table is too large, it may cause online mysql to crash.

method 2: use Count

from django.db.models.aggregates import Count
from random import randint

class PaintingManager(models.Manager):
    def random(self):
        count = self.aggregate(count=Count('id'))['count']
        random_index = randint(0, count - 1)
        return self.all()[random_index]

class Article(models.Model):
    objects = UsersManager()      

# usage
Article.objects.random()
import random

my_ids = Article.objects.values_list('id', flat=True)
my_ids = list(my_ids)
n = 2
rand_ids = random.sample(my_ids, n)

random_records = Article.objects.filter(id__in=rand_ids)

This method is still the same as the first method. If the amount of data in the table is too large, it will consume more resources.

method 4

import random

max_number =5
article_obj = Article.objects.last()
rand_ids = random.sample(range(article_obj.id), max_number * 4)

random_articles = Article.objects.filter(id__in=rand_ids).values('id', 'title')[:max_number]

This method is better than the third method. As for why the number is four times the desired number, it is to prevent part of the id from being deleted and the data cannot be retrieved.

Please log in to leave a comment.