[Answered ]-Is there a way to rewrite this apparently simple Django snippet so that it doesn't hit the database so much?

2👍

This piece:

followed_by_tom = [
user_ct.get_object_for_this_type(id = x.object_id) for x in   
ToggleProperty.objects.filter(
    property_type = "follow",
    user = tom,
    content_type = ContentType.objects.get_for_model(User))
]

gets all of the User instances which are followed in N queries when it could be done in a single query. In fact you don’t need the instances themselves only the ids to get the Images with the IN query. So you can remove the extra queries in the loop via:

followed_by_tom = ToggleProperty.objects.filter(
    property_type="follow",
    user=tom,
    content_type=ContentType.objects.get_for_model(User)
).values_list('object_id', flat=True)

images = Image.objects.filter(user__in=followed_by_tom)

Since followed_by_tom is never evaluated the ORM should execute this as a single query with a sub-select.

Leave a comment