Django duplicated query causing slow loading

Viewed 27

I'm having trouble finding a solution for duplicated queries, I tried doing this.

Code:

for c in coupons:
    fname = Users.objects.filter(
        id=c['WhoReviewed']).values('first_name')
    lname = Users.objects.filter(
        id=c['WhoReviewed']).values('last_name')

    for f in fname:
        first = f['first_name']
    for l in lname:
        last = l['last_name']

        full = first + ' ' + last
        c['WhoReviewed'] = full

Result:

result

1 Answers

You here make two queries per coupon. You can fetch all the users with one query, and then determine the full names with:

users = Users.objects.filter(
    id__in=[c['WhoReviewed'] for c in coupons]
)
temp = {}
for user in users:
    temp[user.id] = f'{user.first_name} {user.last_name}'

for c in coupons:
    data = temp.get(int(c['WhoReviewed']))
    if data is not None:
        c['WhoReviewed'] = data

The modeling however looks a bit "odd". Normally one should expect that the coupon model (?) has a ForeignKey to the User model to point to the person who reviewed the coupon. You can then use .select_related(…) [Django-doc] to piggyback on the query for the coupons to immediately load the related users as well.

Related