[Fixed]-Fastest way to retrieve newly registered users' instances in Django web app

1👍

Under the assumption that you have many more reads than writes, which is reasonable for a public facing website, the biggest performance gain you can get in the lookup is to keep track of the newest users in a separate model:

class LatestUsers(models.Model):
    latest_users = models.ManyToManyField(User)

This model will keep a list of the latest users that you can put in your context. You should create one, via the admin, or manually:

>>> LatestUsers.objects.create()

Then you can put it in the context:

context["fresh_users"] = LatestUsers.objects.all()[0]

To keep track of new users you should connect to the post_save signal of your User model:

from django.db.models.signals import post_save
# method for updating latest users
def update_latest_users(sender, instance, created, **kwargs):
     if created:
         lu = LatestUsers.objects.all()[0]
         # Limit to maximally track the latest 6 users 
         lu.latest_users = lu.latest_users.order_by('-date_joined')[:5]
         lu.latest_users.add(instance) 

# register the signal
post_save.connect(update_latest_users, sender=User, dispatch_uid="update_latest_users")

This way you keep track of your latest users in a separate table and can look them up efficiently, even with potentially millions of users.

Leave a comment