lundi 27 avril 2020

How can I efficiently sample random posts in Django, when each post uses UUIDs rather than sequential IDs?

I have some post models where the ID is a UUID. Now I want to display some random post proposals the user may also like to see at my post_detail template...

This is how I process the post proposals the user may also like to see at views.py:

def post_proposals():
    post_elements = sorted(
        chain(
            Model1.objects.all(),
            Model2.objects.all(),
            Model3.objects.all()
        )
    )
    post_elements_list = list(post_elements) # Conversion to list is requierd by random
    post_proposals = random.sample(post_elements_list)
    return post_proposals


def post_detail(request, pk):
    ...
  args = {
    'post': post,
    'post_proposals': post_proposals(),
  ...

template.html:

 

The problem now is that this would kill my database performance from my understanding... As soon as I have a lot of posts stored at my database the query will become massive. I first have to get all elements of 3 models and then get 10 random entries from the list each time a post gets displayed to the user.

I also found the following which seems to be quite useful:

https://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/

Sadly I can't use that solution as I work with UUIDs which are non-sequential strings instead of int values I would have with IDs.




Aucun commentaire:

Enregistrer un commentaire