[Fixed]-Speeding up nested Django ORM queries

1πŸ‘

βœ…

[UPDATE]: After some discussion in the comments, the question asked about retrieving (and counting) the ids of the logged out Users (i.e users that don’t have an entry in the Session table at all).

So:

# Get a (flat) list of user ids where the user entry in not null
logged_in_users = Session.objects.filter(user__isnull=False).values_list('user__id', flat=True).distinct()

# Get a (flat) list of user ids excluding the previous logged ones (thus, this list will contain the logged out users)
logged_out_users = User.objects.exclude(id__in=logged_in_users).values_list('id', flat=True).distinct()

# Count the logged out users
logged_out_users_count = logged_out_users.count()

How about this:

# Fetch all user_id values from the Session table where the user ForeignKey has
# no value (thus, it's null)
null_user_ids = Session.objects.filter(user__isnull=True).values_list('user__id', flat=True)

# Count the null users
no_of_users = null_user_ids.count()
πŸ‘€nik_m

Leave a comment