Q:

How to use less database look-ups during filter?

I have a section of code that makes several db calls and I am trying to optimize it. Is there a way to get rid of:
username = users.models.User.objects.filter(groups__name=group)

or..
user_obj = users.models.User.objects.get(username=user)

or combine them so that I am only making one database lookup during this transaction instead of two?
        for group in groups:
            username = users.models.User.objects.filter(groups__name=group)
            for user in username:
                form.instance.unread.add(user)
                user_obj = users.models.User.objects.get(username=user)
                user_obj.send_sms('memo')
                user_obj.send_email('memo')

Is this something I am unnecessarily worrying about?

A:

Combining (from the example code of the question) is not a good idea, its looking up DB even more:
 for group in groups:
        username = users.models.User.objects.filter(groups__name=group)
        for user in username:  # <-- Hitting DB 
            form.instance.unread.add(user)
            user_obj = users.models.User.objects.get(username=user) # <-- DB hit again
            user_obj.send_sms('memo')
            user_obj.send_email('memo')

So, minimum optimization you can do is to evaluate the queryset at first, then iterate through loop:
for group in groups:
    username = list(users.models.User.objects.filter(groups__name=group))
    for user in username:
        form.instance.unread.add(user)
        user.send_sms('memo')
        user.send_email('memo')

More information can be found on documentation regarding how querysets are evaluated.
And IMHO, the most optimum solution is like this(I got rid of the for loop):
for group in groups:
    users = users.models.User.objects.filter(groups__name=group)
    form.instance.unread.add(*users) # unpacking the queryset and passing it through add (m2m) method. Reference: https://stackoverflow.com/a/4959580/2696165
    send_sms('memo', users.values_list('phone_number'))  # you need to convert this method so that it is not attached to user object and can accept a list of phone numbers
    send_email('memo', users.values_list('email')) # you need to convert this method so that it is not attached to user object and can accept a list of emails

